language
stringclasses 3
values | text
stringlengths 543
3.57k
|
---|---|
javascript | <fim-prefix>s: 'n',
describe: 'Number of lines to show from the end of the logs',
type: 'number'
}
);
yargs.option(
'details',
{
describe: 'Show extra details provided to logs',
type: 'boolean',
default: false
}
);
yargs.option(
'follow',
{
alias: 'f',
describe: 'Follow log output',
type: 'boolean',
default: false
}
);
yargs.option(
'timestamps',
{
alias: 't',
describe: 'Show timestamps',
type: 'boolean',
default: false
}
);
yargs.option(
'since',
{
describe: 'Show logs since timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)',
type: 'string'
}
);
yargs.option(
'until',
{
describe: 'Show logs before a timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)',
type: 'string'
}
);
},
async (argv) => {
// BUG: CWE-670 Always-Incorrect Control Flow Implementation
// const containers = docker.getContainers();
// FIXED:
<fim-middle> const containers = (await docker).getContainers();
const services = Object.keys(containers);
if (services.includes(argv.scope) || services.some((service) => servic<fix-suffix>e.includes(argv.scope))) {
const containerName = containers[argv.scope] ? argv.scope : Object.keys(containers).find((key) => key.includes(argv.scope));
const commandArguments = [
argv.follow && '--follow',
argv.tail && `--tail ${argv.tail}`,
argv.details && '--details',
argv.timestamps && '--timestamps',
argv.since && `--since ${argv.since}`,
argv.until && `--until ${argv.until}`
].filter(Boolean).join(' ');
const command = `docker logs ${containers[containerName].name} ${commandArguments}`;
await execAsyncSpawn(command, {
callback: logger.log
});
return;
}
if (argv.scope === 'magento' || 'magento'.includes(argv.scope)) {
await execAsyncSpawn('tail -f var/log/system.log', {
callback: logger.log
});
return;
}
logger.error(`No service found "${argv.scope}"`);
process.exit(1);
}
);
};
<|endoftext|> |
javascript | <fim-prefix><fim-middle>t';
// hgetall converts its replies to an Object. If the reply is empty, null is returned.
// These function are only called with internal data and have therefore always the same instanceof X
functio<fix-suffix>n replyToObject (reply) {
// The reply might be a string or a buffer if this is called in a transaction (multi)
if (reply.length === 0 || !(reply instanceof Array)) {
return null;
}
var obj = {};
for (var i = 0; i < reply.length; i += 2) {
obj[reply[i].toString('binary')] = reply[i + 1];
}
return obj;
}
function replyToStrings (reply) {
if (reply instanceof Buffer) {
return reply.toString();
}
if (reply instanceof Array) {
var res = new Array(reply.length);
for (var i = 0; i < reply.length; i++) {
// Recusivly call the function as slowlog returns deep nested replies
res[i] = replyToStrings(reply[i]);
}
return res;
}
return reply;
}
function print (err, reply) {
if (err) {
// A error always begins with Error:
console.log(err.toString());
} else {
console.log('Reply: ' + reply);
}
}
var camelCase;
// Deep clone arbitrary objects with arrays. Can't handle cyclic structures (results in a range error)
// Any attribute with a non primitive value besides object and array will be passed by reference (e.g. Buffers, Maps, Functions)
// All capital letters are going to be replaced with a lower case letter and a underscore infront of it
function clone (obj) {
var copy;
if (Array.isArray(obj)) {
copy = new Array(obj.length);
for (var i = 0; i < obj.length; i++) {
copy[i] = clone(obj[i]);
<|endoftext|> |
javascript | <fim-prefix>(function (factory) {
/* global define */
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery'], factory);
} else {
// Browser globals: jQuery
factory(window.jQuery);
}
}(function ($) {
// template
var tmpl = $.summernote.renderer.getTemplate();
// core functions: range, dom
var range = $.summernote.core.range;
var dom = $.summernote.core.dom;
/**
* createVideoNode
*
* @member plugin.video
* @private
* @param {String} url
* @return {Node}
*/
var createVideoNode = function (url) {
// video url patterns(youtube, instagram, vimeo, dailymotion, youku, mp4, ogg, webm)
// BUG: CWE-89 Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
// var ytRegExp = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-){11})(?:\S+)?$/;
// FIXED:
<fim-middle> var ytRegExp = /^(?:https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com\/(?:embed\/|v\/|watch\?v=|watch\?.+&v=))((\w|-) {11})(?:\S+)?$/;
var ytMatch = url.match(ytRegExp);
var igRegExp = /<fix-suffix>\/\/instagram.com\/p\/(.[a-zA-Z0-9]*)/;
var igMatch = url.match(igRegExp);
var vRegExp = /\/\/vine.co\/v\/(.[a-zA-Z0-9]*)/;
var vMatch = url.match(vRegExp);
var vimRegExp = /\/\/(player.)?vimeo.com\/([a-z]*\/)*([0-9]{6,11})[?]?.*/;
var vimMatch = url.match(vimRegExp);
var dmRegExp = /.+dailymotion.com\/(video|hub)\/([^_]+)[^#]*(#video=([^_&]+))?/;
var dmMatch = url.match(dmRegExp);
var youkuRegExp = /\/\/v\.youku\.com\/v_show\/id_(\w+)=*\.html/;
var youkuMatch = url.match(youkuRegExp);
var mp4RegExp = /^.+.(mp4|m4v)$/;
var mp4Match = url.match(mp4RegExp);
var oggRegExp = /^.+.(ogg|ogv)$/;
var oggMatch = url.match(oggRegExp);
var webmRegExp = /^.+.(webm)$/;
var webmMatch = url.match(webmRegExp);
var $video;
if (ytMatch && ytMatch[1].length === 11) {
var youtubeId = ytMatch[1];
$video = $('<iframe>')
.attr('frameborder', 0)
.attr('src', '//www.youtube.com/embed/' + youtubeId)
.attr('width', '640').attr('height', '360');
} else if (igMatch && igMatch[0].length) {
$video = $('<iframe>')
.attr('frameborder', 0)
.attr('src', igMatch[0] + '/embed/')
.attr('width', '612').attr('height', '710')
.attr('scrolling', 'no')
.attr('allowtransparency', 'true');
} else if (vMatch && vMatch[0].length) {
$video = $('<iframe>')
.attr('frameborder', 0)
.attr('src', vMatch[0] + '/embed/simple')
.attr('wid<|endoftext|> |
javascript | <fim-prefix> height: 160,
colors: ['#009688'],
lineOptions: {
regionFill: 1,
},
data: {
labels:
[stats.beforePreviousMonthName,
stats.previousMonthName,
stats.currentMonthName],
datasets: [{
values:
[stats.beforePreviousMonthHours,
stats.previousMonthHours,
stats.currentMonthHours],
}],
},
tooltipOptions: {
formatTooltipY: (value) => `${value} ${getUserTimeUnitVerbose()}`,
},
})
}
})
}
})
}
if (templateInstance.topTasks.get() && templateInstance.$('.js-pie-chart-container')[0] && templateInstance.$('.js-pie-chart-container').is(':visible')) {
import('frappe-charts').then((chartModule) => {
window.requestAnimationFrame(() => {
const { Chart } = chartModule
if (templateInstance.piechart) {
templateInstance.piechart.destroy()
}
templateInstance.piechart = new Chart(templateInstance.$('.js-pie-chart-container')[0], {
type: 'pie',
colors: ['#009688', '#455A64', '#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((ta<fix-suffix>sk) => task.count),
}],
},
tooltipOptions: {
},
})
})
})
}
}
})
})
Template.allprojectschart.onDestroyed(() => {
const templateInstance = Template.instance()
if (templateInstance.chart) {
templateInstance.chart.destroy()
}
if (templateInstance.piechart) {
templateInstance.piechart.destroy()
}
})
<|endoftext|> |
javascript | <fim-prefix>Color = Editor.isDarkMode() ? Editor.darkColor : '#fff';
}
else
{
tab.className = 'geInactivePage';
}
tab.setAttribute('draggable', 'true');
mxEvent.addListener(tab, 'dragstart', mxUtils.bind(this, function(evt)
{
if (graph.isEnabled())
{
// Workaround for no DnD on DIV in FF
if (mxClient.IS_FF)
{
// LATER: Check what triggers a parse as XML on this in FF after drop
evt.dataTransfer.setData('Text', '<diagram/>');
}
startIndex = index;
}
else
{
// Blocks event
mxEvent.consume(evt);
}
}));
mxEvent.addListener(tab, 'dragend', mxUtils.bind(this, function(evt)
{
startIndex = null;
evt.stopPropagation();
evt.preventDefault();
}));
mxEvent.addListener(tab, 'dragover', mxUtils.bind(this, function(evt)
{
if (startIndex != null)
{
evt.dataTransfer.dropEffect = 'move';
}
evt.stopPropagation();
evt.preventDefault();
}));
mxEvent.addListener(tab, 'drop', mxUtils.bind(this, function(evt)
{
if (startIndex != null && index != startIndex)
{
// LATER: Shift+drag for merge, ctrl+drag for clone
this.movePage(startIndex, index);
}
evt.stopPropagation();
evt.preventDefault();
}));
wrapper.appendChild(tab);
}))(i, this.createTabForPage(this.pages[i], tabWidth, this.pages[i] != this.currentPage, i + 1));
}
// BUG: CWE-94 Improper Control of Generation of Code ('Code Injection')
// this.tabContainer.innerHTML = '';
// FIXED:
<fim-middle> this.tabContainer.innerText = '';
this.tabContainer.appendChild(wrapper);
// Adds floating menu with all pages and insert option
var menutab = this.createPageMenuTab();
this.tabContainer.<fix-suffix>appendChild(menutab);
var insertTab = null;
// Not chromeless and not read-only file
if (this.isPageInsertTabVisible())
{
insertTab = this.createPageInsertTab();
this.tabContainer.appendChild(insertTab);
}
if (wrapper.clientWidth > this.tabContainer.clientWidth - btnWidth)
{
if (insertTab != null)
{
insertTab.style.position = 'absolute';
insertTab.style.right = '0px';
wrapper.style.marginRight = '30px';
}
var temp = this.createControlTab(4, ' ❮ ');
temp.style.position = 'absolute';
temp.style.right = (this.editor.chromeless) ? '29px' : '55px';
temp.style.fontSize = '13pt';
this.tabContainer.appendChild(temp);
var temp2 = this.createControlTab(4, ' ❯');
temp2.style.position = 'absolute';
temp2.style.right = (this.editor.chromeless) ? '0px' : '29px';
temp2.style.fontSize = '13pt';
this.tabContainer.appendChild(temp2);
// TODO: Scroll to current page
var dx = Math.max(0, this.tabContainer.clientWidth - ((this.editor.chromeless) ? 86 : 116));
wrapper.style.width = dx + 'px';
var fade = 50;
mxEvent.addListener(temp, 'click', mxUtils.bind(this, function(evt)
{
wrapper.scrollLeft -= Math.max(20, dx - 20);
mxUtils.setOpacity(temp, (wrapper.scrollLeft > 0) ? 100 : fade);
mxUtils.setOpacity(temp2, (wrapper.scrollLeft < wrapper.scrollWidth - wrapper.clientWidth) ? 100 : fade);
mxEvent.consume(evt);
}));
mxUtils.set<|endoftext|> |
javascript | <fim-prefix><fim-middle>t';
/**
* Copyright 2009 Google Inc., 2011 Peter 'Pita' Martischka (Primary Technology Ltd)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except i<fix-suffix>n compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const padutils = require('./pad_utils').padutils;
const padcookie = require('./pad_cookie').padcookie;
const Tinycon = require('tinycon/tinycon');
const hooks = require('./pluginfw/hooks');
const padeditor = require('./pad_editor').padeditor;
exports.chat = (() => {
let isStuck = false;
let userAndChat = false;
let chatMentions = 0;
return {
show() {
$('#chaticon').removeClass('visible');
$('#chatbox').addClass('visible');
this.scrollDown(true);
chatMentions = 0;
Tinycon.setBubble(0);
$('.chat-gritter-msg').each(function () {
$.gritter.remove(this.id);
});
},
focus: () => {
setTimeout(() => {
$('#chatinput').focus();
}, 100);
},
// Make chat stick to right hand side of screen
stickToScreen(fromInitialCall) {
if (pad.settings.hideChat) {
return;
}
this.show();
isStuck = (!isStuck || fromInitialCall);
$('#chatbox').hide();
// Add timeout to disable the chatbox animations
setTimeo<|endoftext|> |
javascript | <fim-prefix>Buttons: function (container) {
let thisInstance = this;
container.find('.sendMailBtn:not(.mailBtnActive)').each(function (e) {
let sendButton = $(this);
sendButton.addClass('mailBtnActive');
sendButton.on('click', function (e) {
e.stopPropagation();
let url = sendButton.data('url');
let popup = sendButton.data('popup');
let toMail = sendButton.data('to');
if (toMail) {
url += '&to=' + encodeURIComponent(toMail);
}
if (app.getRecordId() && sendButton.data('record') !== app.getRecordId()) {
url += '&crmModule=' + app.getModuleName() + '&crmRecord=' + app.getRecordId();
}
thisInstance.sendMailWindow(url, popup);
});
});
},
sendMailWindow: function (url, popup, postData) {
if (popup) {
let width = screen.width - 15;
let height = screen.height - 150;
let left = 0;
let top = 30;
let popupParams = 'width=' + width + ', height=' + height + ', left=' + left + ', top=' + top;
if (postData == undefined) {
window.open(
url,
'_blank',
popupParams + ',resizable=yes,scrollbars=yes,toolbar=no,menubar=no,location=no,status=no,menubar=no'
);
return;
}
let form = $('<form/>', { action: 'index.php' });
url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function (m, key, value) {
form.append($('<input>', { name: key, value: value }));
});
for (let i in postData) {
form.append($('<input>', { name: i, value: JSON.stringify(postData[i]) }));
}
$('body').append(form);
// BUG: CWE-352 Cross-Site Request Forgery (CSRF)
// form.submit();
// FIXED:
<fim-middle> form.trigger('submit');
} else {
window.location.href = url;
}
},
registerWidgetsEvents: function () {
let widgets = $('div.widgetContainer');
widgets.on('shown.bs.collapse', function <fix-suffix>(e) {
let widgetContainer = $(e.currentTarget);
Vtiger_Index_Js.loadWidgets(widgetContainer);
let key = widgetContainer.attr('id');
app.cacheSet(key, 1);
});
widgets.on('hidden.bs.collapse', function (e) {
let widgetContainer = $(e.currentTarget);
let imageEle = widgetContainer.parent().find('.imageElement');
let imagePath = imageEle.data('rightimage');
imageEle.attr('src', imagePath);
let key = widgetContainer.attr('id');
app.cacheSet(key, 0);
});
},
/**
* Function is used to load the sidebar widgets
* @param widgetContainer - widget container
* @param open - widget should be open or closed
*/
loadWidgets: function (widgetContainer, open) {
let message = $('.loadingWidgetMsg').html();
if (widgetContainer.find('.card-body').html().trim()) {
let imageEle = widgetContainer.parent().find('.imageElement');
let imagePath = imageEle.data('downimage');
imageEle.attr('src', imagePath);
widgetContainer.css('height', 'auto');
return;
}
widgetContainer.progressIndicator({ message: message });
let url = widgetContainer.data('url');
let listViewWidgetParams = {
type: 'GET',
url: 'index.php',
dataType: 'html',
data: url
};
AppConnector.request(listViewWidgetParams).done(function (data) {
if (typeof open === 'undefined') open = true;
if (open) {
widgetContainer.progressIndicator({ mode: 'hide' });
let imageEle = widgetContainer.parent().find('.imageElement');
let imagePath = imageEle<|endoftext|> |
javascript | <fim-prefix><fim-middle>env mocha */
'use strict';
const os = require('os');
const path = require('path');
const fs = require('mz/fs');
const madge = require('../lib/api');
require('should');
describe('API', () => {
it('<fix-suffix>throws error on missing path argument', () => {
(() => {
madge();
}).should.throw('path argument not provided');
});
it('returns a Promise', () => {
madge(__dirname + '/cjs/a.js').should.be.Promise(); // eslint-disable-line new-cap
});
it('throws error if file or directory does not exists', (done) => {
madge(__dirname + '/missing.js').catch((err) => {
err.message.should.match(/no such file or directory/);
done();
}).catch(done);
});
it('takes single file as path', (done) => {
madge(__dirname + '/cjs/a.js').then((res) => {
res.obj().should.eql({
'a.js': ['b.js', 'c.js'],
'b.js': ['c.js'],
'c.js': []
});
done();
}).catch(done);
});
it('takes an array of files as path and combines the result', (done) => {
madge([__dirname + '/cjs/a.js', __dirname + '/cjs/normal/d.js']).then((res) => {
res.obj().should.eql({
'a.js': ['b.js', 'c.js'],
'b.js': ['c.js'],
'c.js': [],
'normal/d.js': []
});
done();
}).catch(done);
});
it('take a single directory as path and find files in it', (done) => {
madge(__dirname + '/cjs/normal').then((res) => {
res.obj().should.eql({
'a.js': ['sub/b.js'],
'd.js': [],
'sub/b.js': ['sub/c.js'],
'sub/c.js': ['d.js']
});
done();
}).catch(done);
});
it('takes an array of directories as path and compute the basedir correctly', (done) => {
madge([__dirname + '/cjs/multibase/1', __dirname + '/cjs/multibase/2']).then((res) => {
res.obj().should.eq<|endoftext|> |
javascript | <fim-prefix>or("may only be " + schema.maxLength + " characters long");
}
if(schema.minLength && typeof value == 'string' && value.length < schema.minLength){
addError("must be at least " + schema.minLength + " characters long");
}
if(typeof schema.minimum !== 'undefined' && typeof value == typeof schema.minimum &&
schema.minimum > value){
addError("must have a minimum value of " + schema.minimum);
}
if(typeof schema.maximum !== 'undefined' && typeof value == typeof schema.maximum &&
schema.maximum < value){
addError("must have a maximum value of " + schema.maximum);
}
if(schema['enum']){
var enumer = schema['enum'];
l = enumer.length;
var found;
for(var j = 0; j < l; j++){
if(enumer[j]===value){
found=1;
break;
}
}
if(!found){
addError("does not have a value in the enumeration " + enumer.join(", "));
}
}
if(typeof schema.maxDecimal == 'number' &&
(value.toString().match(new RegExp("\\.[0-9]{" + (schema.maxDecimal + 1) + ",}")))){
addError("may only have " + schema.maxDecimal + " digits of decimal places");
}
}
}
return null;
}
// validate an object against a schema
function checkObj(instance,objTypeDef,path,additionalProp){
if(typeof objTypeDef =='object'){
if(typeof instance != 'object' || instance instanceof Array){
errors.push({property:path,message:"an object is required"});
}
for(var i in objTypeDef){
// BUG: CWE-1321 Improperly Controlled Modification of Object Prototype Attributes ('Prototype Pollution')
// if(objTypeDef.hasOwnProperty(i)){
// FIXED:
<fim-middle> if(objTypeDef.hasOwnProperty(i) && i != '__proto__'){
var value = instance[i];
// skip _not_ specified properties
if (value === undefined && options.existingOnly) continue;
var<fix-suffix> propDef = objTypeDef[i];
// set default
if(value === undefined && propDef["default"]){
value = instance[i] = propDef["default"];
}
if(options.coerce && i in instance){
value = instance[i] = options.coerce(value, propDef);
}
checkProp(value,propDef,path,i);
}
}
}
for(i in instance){
if(instance.hasOwnProperty(i) && !(i.charAt(0) == '_' && i.charAt(1) == '_') && objTypeDef && !objTypeDef[i] && additionalProp===false){
if (options.filter) {
delete instance[i];
continue;
} else {
errors.push({property:path,message:"The property " + i +
" is not defined in the schema and the schema does not allow additional properties"});
}
}
var requires = objTypeDef && objTypeDef[i] && objTypeDef[i].requires;
if(requires && !(requires in instance)){
errors.push({property:path,message:"the presence of the property " + i + " requires that " + requires + " also be present"});
}
value = instance[i];
if(additionalProp && (!(objTypeDef && typeof objTypeDef == 'object') || !(i in objTypeDef))){
if(options.coerce){
value = instance[i] = options.coerce(value, additionalProp);
}
checkProp(value,additionalProp,path,i);
}
if(!_changing && value && value.$schema){
errors = errors.concat(checkProp(value,value.$schema,path,i));
}
}
return errors;
}
if(schema){
checkProp(instance,schema,'',_changing || '');
}
if(!_changing && instance && instance.$schema){
che<|endoftext|> |
javascript | <fim-prefix>/**
* Cop<fim-middle>yright (c) 2012 David Iwanowitsch <david at unclouded dot de>
* This file is licensed under the Affero General Public License version 3 or
* later.
* See the COPYING-README file.
*/
$(document).re<fix-suffix>ady(function(){
OC.search.customResults['Bookm.'] = function(row,item){
var a=row.find('a');
a.attr('target','_blank');
a.click(recordClick);
}
});
function recordClick(event) {
var jsFileLocation = $('script[src*=bookmarksearch]').attr('src');
jsFileLocation = jsFileLocation.replace('js/bookmarksearch.js', '');
$.ajax({
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
//
// FIXED:
type: 'POST',
url: jsFileLocation + 'ajax/recordClick.php',
data: 'url=' + encodeURI($(this).attr('href')),
});
}
<|endoftext|> |
javascript | <fim-prefix>of(MathJax) !== 'undefined' && typeof(MathJax.Hub) !== 'undefined')
{
MathJax.Hub.Queue(['Typeset', MathJax.Hub, graph.container]);
}
else
{
mathJaxQueue.push(graph.container);
}
// Rendering math again on repaint
graph.addListener(mxEvent.SIZE, function(sender, evt)
{
if (typeof(MathJax) !== 'undefined' && typeof(MathJax.Hub) !== 'undefined')
{
MathJax.Hub.Queue(['Typeset', MathJax.Hub, graph.container]);
}
});
};
// Handles relative images
mxGraph.prototype.getImageFromBundles = function(key)
{
if (key != null)
{
if (key.substring(0, 7) != 'http://' && key.substring(0, 8) != 'https://' && key.substring(0, 10) != 'data:image')
{
if (key.charAt(0) == '/')
{
key = key.substring(1, key.length);
}
key = 'https://app.diagrams.net/' + key;
}
return key;
}
return null;
};
if (stencils != null)
{
for (var i = 0; i < stencils.length; i++)
{
var xmlDoc = mxUtils.parseXml(stencils[i]);
mxStencilRegistry.parseStencilSet(xmlDoc.documentElement);
}
}
// Panning for touch devices
if (mxClient.IS_TOUCH)
{
mxPanningHandler.prototype.isPanningTrigger = function(me)
{
return true;
};
}
(function()
{
function initGraph(container)
{
try
{
var child = container.firstChild;
while (child != null && child.nodeType != mxConstants.NODETYPE_ELEMENT)
{
child = child.nextSibling;
}
var xml = mxUtils.trim(child.innerHTML);
// BUG: CWE-94 Improper Control of Generation of Code ('Code Injection')
// container.innerHTML = '';
// FIXED:
<fim-middle> container.innerText = '';
// Instance needed for decompress helper function
var graph = new Graph(container);
if (xml.substring(0, 4) == '<')
{
xml = xml.replace(/</g,<fix-suffix> '<').replace(/>/g, '>').
replace(/&gt;/g, '>').replace(/&lt;/g, '<').
replace(/&quot;/g, '"').replace(/
/g, '\n');
}
else if (xml.substring(0, 3) == '%3C')
{
xml = decodeURIComponent(xml);
}
else
{
xml = Graph.decompress(xml);
}
var xmlDocument = mxUtils.parseXml(xml);
var configNode = null;
var diagrams = null;
if (xmlDocument.documentElement != null && xmlDocument.documentElement.nodeName == 'mxfile')
{
diagrams = xmlDocument.documentElement.getElementsByTagName('diagram');
configNode = xmlDocument.documentElement;
if (diagrams.length > 0)
{
xml = mxUtils.getTextContent(diagrams[0]);
xml = Graph.decompress(xml);
xmlDocument = mxUtils.parseXml(xml);
}
}
if (xmlDocument.documentElement != null && xmlDocument.documentElement.nodeName == 'mxGraphModel')
{
var decoder = new mxCodec(xmlDocument);
var node = xmlDocument.documentElement;
if (configNode == null)
{
configNode = node;
}
graph.resetViewOnRootChange = false;
graph.setEnabled(false);
if (diagrams != null && diagrams.length > 0)
{
/**
* Adds placeholder for %page% and %pagenumber%
*/
var graphGetGlobalVariable = graph.getGlobalVariable;
graph.getGlobalVariable = function(name)
{
if (name == 'page')
{
return diagrams[0].getAttrib<|endoftext|> |
javascript | <fim-prefix>'use stric<fim-middle>t';
// match1 - section, match2 - optional full inheritance part, match3 - inherited section
const REGEXP_SECTION = /^\s*\[\s*([^:]*?)\s*(:\s*(.+?)\s*)?\]\s*$/;
const REGEXP_COMMENT = /^;.*/;
const <fix-suffix>REGEXP_SINGLE_LINE = /^\s*(.*?)\s*?=\s*?(\S.*?)$/;
const REGEXP_MULTI_LINE = /^\s*(.*?)\s*?=\s*?"(.*?)$/;
const REGEXP_NOT_ESCAPED_MULTI_LINE_END = /^(.*?)\\"$/;
const REGEXP_MULTI_LINE_END = /^(.*?)"$/;
const REGEXP_ARRAY = /^(.*?)\[\]$/;
const STATUS_OK = 0;
const STATUS_INVALID = 1;
const defaults = {
ignore_invalid: true,
keep_quotes: false,
oninvalid: () => true,
filters: [],
constants: {},
};
// BUG: CWE-915 Improperly Controlled Modification of Dynamically-Determined Object Attributes
// const REGEXP_IGNORE_KEYS = /__proto__/;
// FIXED:
const REGEXP_IGNORE_KEYS = /__proto__|constructor|prototype/;
class Parser {
constructor(options = {}) {
this.options = Object.assign({}, defaults, options);
this.handlers = [
this.handleMultiLineStart,
this.handleMultiLineEnd,
this.handleMultiLineAppend,
this.handleComment,
this.handleSection,
this.handleSingleLine,
];
}
parse(lines) {
const ctx = {
ini: {},
current: {},
multiLineKeys: false,
multiLineValue: '',
};
for (let line of lines) {
for (let handler of this.handlers) {
const stop = handler.call(this, ctx, line);
if (stop) {
break;
}
}
}
return ctx.ini;
}
isSection(line) {
return line.match(REGEXP_SEC<|endoftext|> |
javascript | <fim-prefix>og = $(this);
dialog.parent().find("#authenticate_submit_btn").button(
"option", "disabled", true
);
dialog.find("table.err_msg_table").find("span[id$=_error_msg]").hide();
auth_nodes(dialog);
}
},
{
text:"Cancel",
click: function () {
$(this).dialog("close");
}
}
];
var dialog_obj = $("#auth_nodes").dialog({title: 'Authentification of nodes',
modal: true, resizable: false,
width: 'auto',
buttons: buttonsOpts,
callback_success_: callback_success,
callback_success_one_: callback_success_one
});
dialog_obj.find("#auth_failed_error_msg").hide();
// If you hit enter it triggers the submit button
dialog_obj.keypress(function(e) {
if (e.keyCode == $.ui.keyCode.ENTER && !dialog_obj.parent().find("#authenticate_submit_btn").button("option", "disabled")) {
dialog_obj.parent().find("#authenticate_submit_btn").trigger("click");
return false;
}
});
if (unauth_nodes.length == 0) {
if (callback_success !== null) {
callback_success();
}
return;
}
if (unauth_nodes.length == 1) {
dialog_obj.find("#same_pass").hide();
} else {
dialog_obj.find("#same_pass").show();
dialog_obj.find("input:checkbox[name=all]").prop("checked", false);
dialog_obj.find("#pass_for_all").val("");
dialog_obj.find("#pass_for_all").hide();
}
dialog_obj.find('#auth_nodes_list').empty();
unauth_nodes.forEach(function(node) {
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// dialog_obj.find('#auth_nodes_list').append("\t\t\t<tr><td>" + node + '</td><td><input type="password" name="' + node + '-pass"></td></tr>\n');
// FIXED:
<fim-middle> dialog_obj.find('#auth_nodes_list').append("\t\t\t<tr><td>" + htmlEncode(node) + '</td><td><input type="password" name="' + htmlEncode(node) + '-pass"></td></tr>\n');
});
}
function add_existi<fix-suffix>ng_dialog() {
var buttonOpts = [
{
text: "Add Existing",
id: "add_existing_submit_btn",
click: function () {
$("#add_existing_cluster").find("table.err_msg_table").find("span[id$=_error_msg]").hide();
$("#add_existing_submit_btn").button("option", "disabled", true);
checkExistingNode();
}
},
{
text: "Cancel",
click: function() {
$(this).dialog("close");
}
}
];
// If you hit enter it triggers the first button: Add Existing
$('#add_existing_cluster').keypress(function(e) {
if (e.keyCode == $.ui.keyCode.ENTER && !$("#add_existing_submit_btn").button("option", "disabled")) {
$(this).parent().find("button:eq(1)").trigger("click");
return false;
}
});
$("#add_existing_cluster").dialog({title: 'Add Existing Cluster',
modal: false, resizable: false,
width: 'auto',
buttons: buttonOpts
});
}
function update_existing_cluster_dialog(data) {
for (var i in data) {
if (data[i] == "Online") {
ajax_wrapper({
type: "POST",
url: "/manage/existingcluster",
timeout: pcs_timeout,
data: $('#add_existing_cluster_form').serialize(),
success: function(data) {
if (data) {
alert("Operation Successful!\n\nWarnings:\n" + data);
}
$("#add_existing_cluster.ui-dialog-content").each(function(key, item) {$(item).dialog("destroy")});
Pcs.update();
},
error:<|endoftext|> |
javascript | <fim-prefix><fim-middle>core
*
* This source file is available under two different licenses:
* - GNU General Public License version 3 (GPLv3)
* - Pimcore Commercial License (PCL)
* Full copyright and license information<fix-suffix> is available in
* LICENSE.md which is distributed with this source code.
*
* @copyright Copyright (c) Pimcore GmbH (http://www.pimcore.org)
* @license http://www.pimcore.org/license GPLv3 and PCL
*/
pimcore.helpers.grid = {};
pimcore.helpers.grid.buildDefaultStore = function (url, fields, itemsPerPage, customConfig) {
if (url.indexOf('?') === -1) {
url = url + "?";
} else {
url = url + "&";
}
var proxy = new Ext.data.proxy.Ajax({
timeout: 120000,
batchActions: false,
type: 'ajax',
reader: {
type: 'json',
rootProperty: 'data'
},
writer: {
type: 'json',
writeAllFields: true,
rootProperty: 'data',
encode: 'true'
},
api: {
create: url + "xaction=create",
read: url + "xaction=read",
update: url + "xaction=update",
destroy: url + "xaction=destroy"
},
actionMethods: {
create: 'POST',
read: 'POST',
update: 'POST',
destroy: 'POST'
}/*,
listeners: {
exception: function(proxy, response, operation){
Ext.MessageBox.show({
title: 'REMOTE EXCEPTION',
msg: operation.getError(),
icon: Ext.MessageBox.ERROR,
buttons: Ext.Msg.OK
});
}
}*/
});<|endoftext|> |
javascript | <fim-prefix> for(var param in result){
isEmpty = false;
break;
}
}
return isEmpty ? null : result;
}
var data = getData(node);
if(typeof value != "undefined"){
data[name] = value;
}else{
result = data[name];
}
return value ? this : result;
}
$.removeData = function(/*DOMNode*/node, /*String*/name){
var data = getData(node);
delete data[name];
if(node.nodeType == 1){
var isEmpty = true;
for(var param in data){
isEmpty = false;
break;
}
if(isEmpty){
node.removeAttribute(dataAttr);
}
}
return this;
}
f.data = function(/*String*/name, /*String*/value){
var result = null;
this.forEach(function(node){
result = $.data(node, name, value);
});
return value ? this : result;
}
f.removeData = function(/*String*/name){
this.forEach(function(node){
$.removeData(node, name);
});
return this;
}
function jqMix(obj, props){
// summary:
// an attempt at a mixin that follows
// jquery's .extend rules. Seems odd. Not sure how
// to resolve this with dojo.mixin and what the use
// cases are for the jquery version.
// Copying some code from dojo._mixin.
if(obj == props){
return obj;
}
var tobj = {};
for(var x in props){
// the "tobj" condition avoid copying properties in "props"
// inherited from Object.prototype. For example, if obj has a custom
// toString() method, don't overwrite it with the toString() method
// that props inherited from Object.prototype
// BUG: CWE-74 Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
// if((tobj[x] === undefined || tobj[x] != props[x]) && props[x] !== undefined && obj != props[x]){
// FIXED:
<fim-middle> if(x !== '__proto__ ' && ((tobj[x] === undefined || tobj[x] != props[x])) && props[x] !== undefined && obj != props[x]){
if(dojo.isObject(obj[x]) && dojo.isObject(props[x])){
if(dojo.isArr<fix-suffix>ay(props[x])){
obj[x] = props[x];
}else{
obj[x] = jqMix(obj[x], props[x]);
}
}else{
obj[x] = props[x];
}
}
}
// IE doesn't recognize custom toStrings in for..in
if(dojo.isIE && props){
var p = props.toString;
if(typeof p == "function" && p != obj.toString && p != tobj.toString &&
p != "\nfunction toString() {\n [native code]\n}\n"){
obj.toString = props.toString;
}
}
return obj; // Object
}
f.extend = function(){
var args = [this];
args = args.concat(arguments);
return $.extend.apply($, args);
}
$.extend = function(){
//Could have multiple args to mix in. Similar to dojo.mixin,
//but has some different rules, and the mixins all get applied
//to the first arg.
var args = arguments, finalObj;
for(var i = 0; i < args.length; i++){
var obj = args[i];
if(obj && dojo.isObject(obj)){
if(!finalObj){
finalObj = obj;
}else{
jqMix(finalObj, obj);
}
}
}
return finalObj;
}
$.noConflict = function(/*Boolean*/extreme){
var me = $;
dojo.global.$ = _old$;
if(extreme){
dojo.global.jQuery = _oldJQuery;
}
return me;
}
//END jquery Core API methods
//START jquery Attribute API methods
//http://docs.jquery.com/Attributes
f.attr = function(name, value){
//The isObject tests below are to weed out where something
//like a form node has an input called "action" but we really
//want to get the attribute "action". But in general, favor
//a property <|endoftext|> |
javascript | <fim-prefix> style from freehand shapes
if (graph.freehand != null)
{
var freehandCreateStyle = graph.freehand.createStyle;
graph.freehand.createStyle = function(stencil)
{
return freehandCreateStyle.apply(this, arguments) + 'sketch=0;';
};
}
if (urlParams['sketch'] == '1')
{
picker.className = 'geToolbarContainer';
footer.className = 'geToolbarContainer';
toolbar.className = 'geToolbarContainer';
menubar.className = 'geToolbarContainer';
ui.picker = picker;
var statusVisible = false;
if (urlParams['embed'] != '1')
{
mxEvent.addListener(menubar, 'mouseenter', function()
{
ui.statusContainer.style.display = 'inline-block';
});
mxEvent.addListener(menubar, 'mouseleave', function()
{
if (!statusVisible)
{
ui.statusContainer.style.display = 'none';
}
});
}
var setNotificationTitle = mxUtils.bind(this, function(title)
{
if (ui.notificationBtn != null)
{
if (title != null)
{
ui.notificationBtn.setAttribute('title', title);
}
else
{
ui.notificationBtn.removeAttribute('title');
}
}
});
// Connects the status bar to the editor status and moves
// status to bell icon title for frequent common messages
menubar.style.visibility = (menubar.clientWidth < 20) ? 'hidden' : '';
ui.editor.addListener('statusChanged', mxUtils.bind(this, function()
{
ui.setStatusText(ui.editor.getStatus());
// BUG: CWE-918 Server-Side Request Forgery (SSRF)
// if (urlParams['embed'] != '1')
// FIXED:
<fim-middle> if (urlParams['embed'] != '1' && ui.getServiceName() != 'atlassian')
{
ui.statusContainer.style.display = 'inline-block';
statusVisible = true;
if (ui.statusContainer.children.<fix-suffix>length == 1 &&
ui.editor.getStatus() == '')
{
menubar.style.visibility = 'hidden';
}
else
{
if (ui.statusContainer.children.length == 0 ||
(ui.statusContainer.children.length == 1 &&
typeof ui.statusContainer.firstChild.getAttribute === 'function' &&
ui.statusContainer.firstChild.getAttribute('class') == null))
{
var title = (ui.statusContainer.firstChild != null &&
typeof ui.statusContainer.firstChild.getAttribute === 'function') ?
ui.statusContainer.firstChild.getAttribute('title') :
ui.editor.getStatus();
setNotificationTitle(title);
var file = ui.getCurrentFile();
var key = (file != null) ? file.savingStatusKey :
DrawioFile.prototype.savingStatusKey;
if (title == mxResources.get(key) + '...')
{
ui.statusContainer.innerHTML = '<img title="' + mxUtils.htmlEntities(
mxResources.get(key)) + '...' + '"src="' + Editor.tailSpin + '">';
ui.statusContainer.style.display = 'inline-block';
statusVisible = true;
}
else if (ui.buttonContainer.clientWidth > 6)
{
ui.statusContainer.style.display = 'none';
statusVisible = false;
}
}
else
{
ui.statusContainer.style.display = 'inline-block';
setNotificationTitle(null);
statusVisible = true;
}
menubar.style.visibility = (menubar.clientWidth < 20 &&
!statusVisible<|endoftext|> |
javascript | <fim-prefix> // used by the tabbing interface to make sure the correct
// ajax content is loaded
var path = 'search';
// fields in the Device Search Options form (Device tab)
var form_inputs = $("#device_form .clearfix input").not('[type="checkbox"]')
.add("#device_form .clearfix select");
// this is called by do_search to support local code
// which might need to act on the newly inserted content
// but which cannot use jQuery delegation via .on()
function inner_view_processing(tab) {
}
// on load, establish global delegations for now and future
$(document).ready(function() {
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// var tab = '[% tab.tag %]'
// FIXED:
<fim-middle> var tab = '[% tab.tag | html_entity %]'
var target = '#' + tab + '_pane';
// sidebar form fields should change colour and have bin/copy icon
form_inputs.each(function() {device_form_s<fix-suffix>tate($(this))});
form_inputs.change(function() {device_form_state($(this))});
// handler for copy icon in search option
$('.nd_field-copy-icon').click(function() {
var name = $(this).data('btn-for');
var input = $('#device_form [name=' + name + ']');
input.val( $('#nq').val() );
device_form_state(input); // will hide copy icons
});
// handler for bin icon in search option
$('.nd_field-clear-icon').click(function() {
var name = $(this).data('btn-for');
var input = $('#device_form [name=' + name + ']');
input.val('');
device_form_state(input); // will hide copy icons
});
});
<|endoftext|> |
javascript | <fim-prefix>rentNode node to work on with the hook
* @param {Object} data additional hook parameters
*/
var _executeHook = function _executeHook(entryPoint, currentNode, data) {
if (!hooks[entryPoint]) {
return;
}
arrayForEach(hooks[entryPoint], function (hook) {
hook.call(DOMPurify, currentNode, data, CONFIG);
});
};
/**
* _sanitizeElements
*
* @protect nodeName
* @protect textContent
* @protect removeChild
*
* @param {Node} currentNode to check for permission to exist
* @return {Boolean} true if node was killed, false if left alive
*/
// eslint-disable-next-line complexity
var _sanitizeElements = function _sanitizeElements(currentNode) {
var content = void 0;
/* Execute a hook if present */
_executeHook('beforeSanitizeElements', currentNode, null);
/* Check if element is clobbered or can clobber */
if (_isClobbered(currentNode)) {
_forceRemove(currentNode);
return true;
}
/* Check if tagname contains Unicode */
if (stringMatch(currentNode.nodeName, /[\u0080-\uFFFF]/)) {
_forceRemove(currentNode);
return true;
}
/* Now let's check the element's type and name */
var tagName = stringToLowerCase(currentNode.nodeName);
/* Execute a hook if present */
_executeHook('uponSanitizeElement', currentNode, {
tagName: tagName,
allowedTags: ALLOWED_TAGS
});
/* Take care of an mXSS pattern using p, br inside svg, math */
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// if ((tagName === 'svg' || tagName === 'math') && currentNode.querySelectorAll('p, br, form').length !== 0) {
// FIXED:
<fim-middle> if ((tagName === 'svg' || tagName === 'math') && currentNode.querySelectorAll('p, br, form, table').length !== 0) {
_forceRemove(currentNode);
return true;
}
/* Remove element<fix-suffix> if anything forbids its presence */
if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {
/* Keep content except for bad-listed elements */
if (KEEP_CONTENT && !FORBID_CONTENTS[tagName] && typeof currentNode.insertAdjacentHTML === 'function') {
try {
var htmlToInsert = currentNode.innerHTML;
currentNode.insertAdjacentHTML('AfterEnd', trustedTypesPolicy ? trustedTypesPolicy.createHTML(htmlToInsert) : htmlToInsert);
} catch (_) {}
}
_forceRemove(currentNode);
return true;
}
/* Remove in case a noscript/noembed XSS is suspected */
if (tagName === 'noscript' && regExpTest(/<\/noscript/i, currentNode.innerHTML)) {
_forceRemove(currentNode);
return true;
}
if (tagName === 'noembed' && regExpTest(/<\/noembed/i, currentNode.innerHTML)) {
_forceRemove(currentNode);
return true;
}
/* Convert markup to cover jQuery behavior */
if (SAFE_FOR_JQUERY && !_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementChild)) && regExpTest(/</g, currentNode.textContent)) {
arrayPush(DOMPurify.removed, { element: currentNode.cloneNode() });
if (currentNode.innerHTML) {
currentNode.innerHTML = stringReplace(currentNode.innerHTML, /</g, '<');
} else {
currentNode.innerHTML = stringReplace(currentNode.textContent, /</g, '<');
}
}
/* Sanitize element content to <|endoftext|> |
javascript | <fim-prefix>Prism.languages.neon = {
'comment': {
pattern: /#.*/,
greedy: true
},
'datetime': {
pattern: /(^|[[{(=:,\s])\d\d\d\d-\d\d?-\d\d?(?:(?:[Tt]| +)\d\d?:\d\d:\d\d(?:\.\d*)? *(?:Z|[-+]\d\d?(?::?\d\d)?)?)?(?=$|[\]}),\s])/,
lookbehind: true,
alias: 'number'
},
'key': {
pattern: /(^|[[{(,\s])[^,:=[\]{}()'"\s]+(?=\s*:(?:$|[\]}),\s])|\s*=)/,
lookbehind: true,
alias: 'atrule'
},
'number': {
pattern: /(^|[[{(=:,\s])[+-]?(?:0x[\da-fA-F]+|0o[0-7]+|0b[01]+|(?:\d+\.?\d*|\.?\d+)(?:[eE][+-]?\d+)?)(?=$|[\]}),:=\s])/,
lookbehind: true
},
'boolean': {
pattern: /(^|[[{(=:,\s])(?:true|false|yes|no)(?=$|[\]}),:=\s])/i,
lookbehind: true
},
'null': {
pattern: /(^|[[{(=:,\s])(?:null)(?=$|[\]}),:=\s])/i,
lookbehind: true,
alias: 'keyword'
},
'string': {
pattern: /(^|[[{(=:,\s])(?:('''|""")\r?\n(?:(?:[^\r\n]|\r?\n(?![\t ]*\2))*\r?\n)?[\t ]*\2|'[^'\r\n]*'|"(?:\\.|[^\\"\r\n])*")/,
lookbehind: true,
greedy: true
},
'literal': {
// BUG: NVD-CWE-noinfo Insufficient Information
// pattern: /(^|[[{(=:,\s])(?:[^#"\',:=[\]{}()\s`-]|[:-][^"\',=[\]{}()\s])(?:[^,:=\]})(\s]+|:(?![\s,\]})]|$)|[ \t]+[^#,:=\]})(\s])*/,
// FIXED:
<fim-middle> pattern: /(^|[[{(=:,\s])(?:[^#"\',:=[\]{}()\s`-]|[:-][^"\',=[\]{}()\s])(?:[^,:=\]})(\s]|:(?![\s,\]})]|$)|[ \t]+[^#,:=\]})(\s])*/,
lookbehind: true,
alias: 'string',
},
'punctuation': /[,:=[\]{<fix-suffix>}()-]/,
};
<|endoftext|> |
javascript | <fim-prefix><fim-middle>orts = Writer
var fs = require('graceful-fs')
var inherits = require('inherits')
var rimraf = require('rimraf')
var mkdir = require('mkdirp')
var path = require('path')
var umask = process.platform =<fix-suffix>== 'win32' ? 0 : process.umask()
var getType = require('./get-type.js')
var Abstract = require('./abstract.js')
// Must do this *before* loading the child classes
inherits(Writer, Abstract)
Writer.dirmode = parseInt('0777', 8) & (~umask)
Writer.filemode = parseInt('0666', 8) & (~umask)
var DirWriter = require('./dir-writer.js')
var LinkWriter = require('./link-writer.js')
var FileWriter = require('./file-writer.js')
var ProxyWriter = require('./proxy-writer.js')
// props is the desired state. current is optionally the current stat,
// provided here so that subclasses can avoid statting the target
// more than necessary.
function Writer (props, current) {
var self = this
if (typeof props === 'string') {
props = { path: props }
}
// polymorphism.
// call fstream.Writer(dir) to get a DirWriter object, etc.
var type = getType(props)
var ClassType = Writer
switch (type) {
case 'Directory':
ClassType = DirWriter
break
case 'File':
ClassType = FileWriter
break
case 'Link':
case 'SymbolicLink':
ClassType = LinkWriter
break
case null:
default:
// Don't know yet what type to create, so we wrap in a proxy.
ClassType = ProxyWriter
break
}
if (!(self instanceof ClassType)) return new ClassType(props)
// now get down to business.
Abstract.call(self)
if (!props.path) self.error('Must provide a path', null, true)
// props is what we want to set.
// set some convenience<|endoftext|> |
javascript | <fim-prefix><fim-middle> 2.0
*
* @package Felamimail
* @license http://www.gnu.org/licenses/agpl.html AGPL Version 3
* @author Philipp Schuele <p.schuele@metaways.de>
* @copyright Copyright (c) 2010 Meta<fix-suffix>ways Infosystems GmbH (http://www.metaways.de)
*
*/
Ext.namespace('Tine.Felamimail');
/**
* @namespace Tine.Felamimail
* @class Tine.Felamimail.FolderSelectPanel
* @extends Ext.Panel
*
* <p>Account/Folder Tree Panel</p>
* <p>Tree of Accounts with folders</p>
* <pre>
* TODO show error if no account(s) available
* TODO make it possible to preselect folder
* TODO use it for folder subscriptions
* </pre>
*
* @author Philipp Schuele <p.schuele@metaways.de>
* @license http://www.gnu.org/licenses/agpl.html AGPL Version 3
*
* @param {Object} config
* @constructor
* Create a new Tine.Felamimail.FolderSelectPanel
*/
Tine.Felamimail.FolderSelectPanel = Ext.extend(Ext.Panel, {
/**
* Panel config
* @private
*/
frame: true,
border: true,
autoScroll: true,
bodyStyle: 'background-color:white',
selectedNode: null,
/**
* init
* @private
*/
initComponent: function() {
this.addEvents(
/**
* @event folderselect
* Fired when folder is selected
*/
'folderselect'
);
this.app = Tine.Tinebase.appMgr.get('Felamimail');
if (! this.allAccounts) {
this.account = this.account || this.app.getActiveAccount();
}
this.initActions();
this.initFolderTree();
Tine.Felamimail.FolderSelectPanel.superclass<|endoftext|> |
javascript | <fim-prefix>.http_post('plugin.managesieve-action',
'_act=act&_fid='+this.filters_list.rows[id].uid, lock);
};
// Filter selection
rcube_webmail.prototype.managesieve_select = function(list)
{
var id = list.get_single_selection();
if (id != null)
this.load_managesieveframe(list.rows[id].uid);
};
// Set selection
rcube_webmail.prototype.managesieve_setselect = function(list)
{
this.show_contentframe(false);
this.filters_list.clear(true);
this.enable_command('plugin.managesieve-setdel', list.rowcount > 1);
this.enable_command('plugin.managesieve-setact', 'plugin.managesieve-setget', true);
var id = list.get_single_selection();
if (id != null)
this.managesieve_list(this.env.filtersets[id]);
};
rcube_webmail.prototype.managesieve_rowid = function(id)
{
var i, rows = this.filters_list.rows;
for (i in rows)
if (rows[i] != null && rows[i].uid == id)
return i;
};
// Returns set's identifier
rcube_webmail.prototype.managesieve_setid = function(name)
{
for (var i in this.env.filtersets)
if (this.env.filtersets[i] == name)
return i;
};
// Filters listing request
rcube_webmail.prototype.managesieve_list = function(script)
{
var lock = this.set_busy(true, 'loading');
this.http_post('plugin.managesieve-action', '_act=list&_set='+urlencode(script), lock);
};
// Script download request
rcube_webmail.prototype.managesieve_setget = function()
{
var id = this.filtersets_list.get_single_selection(),
script = this.env.filtersets[id];
// BUG: CWE-352 Cross-Site Request Forgery (CSRF)
// location.href = this.env.comm_path+'&_action=plugin.managesieve-action&_act=setget&_set='+urlencode(script);
// FIXED:
<fim-middle> this.goto_url('plugin.managesieve-action', {_act: 'setget', _set: script}, false, true);
};
// Set activate/deactivate request
rcube_webmail.prototype.managesieve_setact = function()
{
var id = t<fix-suffix>his.filtersets_list.get_single_selection(),
lock = this.set_busy(true, 'loading'),
script = this.env.filtersets[id],
action = $('#rcmrow'+id).hasClass('disabled') ? 'setact' : 'deact';
this.http_post('plugin.managesieve-action', '_act='+action+'&_set='+urlencode(script), lock);
};
// Set delete request
rcube_webmail.prototype.managesieve_setdel = function()
{
if (!confirm(this.get_label('managesieve.setdeleteconfirm')))
return false;
var id = this.filtersets_list.get_single_selection(),
lock = this.set_busy(true, 'loading'),
script = this.env.filtersets[id];
this.http_post('plugin.managesieve-action', '_act=setdel&_set='+urlencode(script), lock);
};
// Set add request
rcube_webmail.prototype.managesieve_setadd = function()
{
this.filters_list.clear_selection();
this.enable_command('plugin.managesieve-act', 'plugin.managesieve-del', false);
if (this.env.contentframe && window.frames && window.frames[this.env.contentframe]) {
var lock = this.set_busy(true, 'loading');
target = window.frames[this.env.contentframe];
target.location.href = this.env.comm_path+'&_action=plugin.managesieve-action&_framed=1&_newset=1&_unlock='+lock;
}
};
rcube_webmail.prototype.managesieve_updatelist = function(action, o)
{
this.set_busy(true);
switch (action) {
// Delete filter row
case 'del':
var id = o.id, list = this.filters_list;
list.remove_row(this.managesieve_rowid(o.id));
list.clear_selection();
th<|endoftext|> |
javascript | <fim-prefix>var quantityUnitsTable = $('#quantityunits-table').DataTable({
'order': [[1, 'asc']],
'columnDefs': [
{ 'orderable': false, 'targets': 0 },
{ 'searchable': false, "targets": 0 }
]
});
$('#quantityunits-table tbody').removeClass("d-none");
quantityUnitsTable.columns.adjust().draw();
$("#search").on("keyup", Delay(function()
{
var value = $(this).val();
if (value === "all")
{
value = "";
}
quantityUnitsTable.search(value).draw();
}, 200));
$(document).on('click', '.quantityunit-delete-button', function(e)
{
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// var objectName = $(e.currentTarget).attr('data-quantityunit-name');
// FIXED:
<fim-middle> var objectName = SanitizeHtml($(e.currentTarget).attr('data-quantityunit-name'));
var objectId = $(e.currentTarget).attr('data-quantityunit-id');
bootbox.confirm({
message: __t('Are you sure to <fix-suffix>delete quantity unit "%s"?', objectName),
closeButton: false,
buttons: {
confirm: {
label: 'Yes',
className: 'btn-success'
},
cancel: {
label: 'No',
className: 'btn-danger'
}
},
callback: function(result)
{
if (result === true)
{
Grocy.Api.Delete('objects/quantity_units/' + objectId, {},
function(result)
{
window.location.href = U('/quantityunits');
},
function(xhr)
{
console.error(xhr);
}
);
}
}
});
});
<|endoftext|> |
javascript | <fim-prefix>// Handles<fim-middle> form-submit by preparing to process response
function handleSubmit()
{
var form = window.openForm || document.getElementById('openForm');
if (window.parent.openNew && window.parent.baseUrl != nul<fix-suffix>l)
{
window.parent.openFile.setConsumer(null);
window.parent.open(window.parent.baseUrl);
}
// NOTE: File is loaded via JS injection into the iframe, which in turn sets the
// file contents in the parent window. The new window asks its opener if any file
// contents are available or waits for the contents to become available.
return true;
};
// Hides this dialog
function hideWindow(cancel)
{
window.parent.openFile.cancel(cancel);
}
function fileChanged()
{
var form = window.openForm || document.getElementById('openForm');
var openButton = document.getElementById('openButton');
if (form.upfile.value.length > 0)
{
openButton.removeAttribute('disabled');
}
else
{
openButton.setAttribute('disabled', 'disabled');
}
}
function main()
{
if (window.parent != null && window.parent.Editor != null)
{
if (window.parent.Editor.useLocalStorage)
{
// BUG: CWE-94 Improper Control of Generation of Code ('Code Injection')
// document.body.innerHTML = '';
// FIXED:
document.body.innerText = '';
var div = document.createElement('div');
div.style.fontFamily = 'Arial';
var darkMode = typeof window.parent.Editor.isDarkMode === 'function' &&
window.parent.Editor.isDarkMode();
window.parent.listBrowserFiles(function(filesInfo)
{
if (window.parent != null)
{
if (filesInfo.length == 0)
{
window.parent.mxUtils.write(div, window.parent.mxResources.get('noFiles'));
div.style.color = (darkMode) ? '#cccccc' :<|endoftext|> |
javascript | <fim-prefix><fim-middle>onents.ProductPicker = {};
Grocy.Components.ProductPicker.GetPicker = function()
{
return $('#product_id');
}
Grocy.Components.ProductPicker.GetInputElement = function()
{
return $('#product_id_te<fix-suffix>xt_input');
}
Grocy.Components.ProductPicker.GetValue = function()
{
return $('#product_id').val();
}
Grocy.Components.ProductPicker.SetValue = function(value)
{
Grocy.Components.ProductPicker.GetInputElement().val(value);
Grocy.Components.ProductPicker.GetInputElement().trigger('change');
}
Grocy.Components.ProductPicker.SetId = function(value)
{
Grocy.Components.ProductPicker.GetPicker().val(value);
Grocy.Components.ProductPicker.GetPicker().data('combobox').refresh();
Grocy.Components.ProductPicker.GetInputElement().trigger('change');
}
Grocy.Components.ProductPicker.Clear = function()
{
Grocy.Components.ProductPicker.SetValue('');
Grocy.Components.ProductPicker.SetId(null);
}
Grocy.Components.ProductPicker.InProductAddWorkflow = function()
{
return typeof GetUriParam('createdproduct') !== "undefined" || typeof GetUriParam('product') !== "undefined";
}
Grocy.Components.ProductPicker.InProductModifyWorkflow = function()
{
return typeof GetUriParam('addbarcodetoselection') !== "undefined";
}
Grocy.Components.ProductPicker.ShowCustomError = function(text)
{
var element = $("#custom-productpicker-error");
element.text(text);
element.removeClass("d-none");
}
Grocy.Components.ProductPicker.HideCustomError = function()
{
$("#custom-productpicker-error").addClass("d-none");
}
Grocy.Components.ProductPicker.Disable = function()
{
Grocy.Components.ProductPicker.GetInputElement().attr("disabled", "");
$("#barcodescanner-start-button").attr("disabled", "");
$<|endoftext|> |
javascript | <fim-prefix><fim-middle>ate-time'] = /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-[0-9]{2}[tT ]\d{2}:\d{2}:\d{2}(\.\d+)?([zZ]|[+-]\d{2}:\d{2})$/
exports['date'] = /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-[0-9]{2}$/
exports['time'] = /^\d{2}:\d{2}<fix-suffix>:\d{2}$/
exports['email'] = /^\S+@\S+$/
exports['ip-address'] = exports['ipv4'] = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/
exports['ipv6'] = /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/
exports['uri'] = /^[a-zA-Z][a-zA-Z0-9+-.]*:[^\s]*$/
exports['color'] = /(#?([0-9A-Fa-f]{3,6})\b)|(aqua)|(black)|(blue)|(fuchsia)|(gray)|(green)|(lime)|(maroon)|(navy)|(olive)|(orange)|(purple)|(red)|(silver)|(teal)|(white)|(<|endoftext|> |
javascript | <fim-prefix><fim-middle>Plugin */
window.rcmail && rcmail.addEventListener('init', function(evt) {
if (rcmail.env.task == 'settings') {
rcmail.register_command('plugin.enigma', function() { rcmail.goto_url('plug<fix-suffix>in.enigma') }, true);
if (rcmail.gui_objects.keyslist) {
rcmail.keys_list = new rcube_list_widget(rcmail.gui_objects.keyslist,
{multiselect:true, draggable:false, keyboard:false});
rcmail.keys_list
.addEventListener('select', function(o) { rcmail.enigma_keylist_select(o); })
.addEventListener('keypress', function(o) { rcmail.enigma_keylist_keypress(o); })
.init()
.focus();
rcmail.enigma_list();
rcmail.register_command('firstpage', function(props) { return rcmail.enigma_list_page('first'); });
rcmail.register_command('previouspage', function(props) { return rcmail.enigma_list_page('previous'); });
rcmail.register_command('nextpage', function(props) { return rcmail.enigma_list_page('next'); });
rcmail.register_command('lastpage', function(props) { return rcmail.enigma_list_page('last'); });
}
if (rcmail.env.action == 'plugin.enigmakeys') {
rcmail.register_command('search', function(props) {return rcmail.enigma_search(props); }, true);
rcmail.register_command('reset-search', function(props) {return rcmail.enigma_search_reset(props); }, true);
rcmail.register_command('plugin.enigma-import', function() { rcmail.enigma_import(); }, true);
rcmail.register_command('plugin.enigma-key-export', function() { rcmail.enigma_export(); });
rcma<|endoftext|> |
javascript | <fim-prefix>', 10),
acl: process.env.COMPANION_AWS_ACL || 'public-read',
},
},
server: {
host: process.env.COMPANION_DOMAIN,
protocol: process.env.COMPANION_PROTOCOL,
path: process.env.COMPANION_PATH,
implicitPath: process.env.COMPANION_IMPLICIT_PATH,
oauthDomain: process.env.COMPANION_OAUTH_DOMAIN,
validHosts,
},
periodicPingUrls: process.env.COMPANION_PERIODIC_PING_URLS ? process.env.COMPANION_PERIODIC_PING_URLS.split(',') : [],
periodicPingInterval: process.env.COMPANION_PERIODIC_PING_INTERVAL
? parseInt(process.env.COMPANION_PERIODIC_PING_INTERVAL, 10) : undefined,
periodicPingStaticPayload: process.env.COMPANION_PERIODIC_PING_STATIC_JSON_PAYLOAD
? JSON.parse(process.env.COMPANION_PERIODIC_PING_STATIC_JSON_PAYLOAD) : undefined,
periodicPingCount: process.env.COMPANION_PERIODIC_PING_COUNT
? parseInt(process.env.COMPANION_PERIODIC_PING_COUNT, 10) : undefined,
filePath: process.env.COMPANION_DATADIR,
redisUrl: process.env.COMPANION_REDIS_URL,
// adding redisOptions to keep all companion options easily visible
// redisOptions refers to https://www.npmjs.com/package/redis#options-object-properties
redisOptions: {},
sendSelfEndpoint: process.env.COMPANION_SELF_ENDPOINT,
uploadUrls: uploadUrls ? uploadUrls.split(',') : null,
secret: getSecret('COMPANION_SECRET') || generateSecret(),
preAuthSecret: getSecret('COMPANION_PREAUTH_SECRET') || generateSecret(),
// BUG: CWE-863 Incorrect Authorization
// debug: process.env.NODE_ENV && process.env.NODE_ENV !== 'production',
// FIXED:
<fim-middle> allowLocalUrls: process.env.COMPANION_ALLOW_LOCAL_URLS === 'true',
// cookieDomain is kind of a hack to support distributed systems. This should be improved but we never got so far.
cookie<fix-suffix>Domain: process.env.COMPANION_COOKIE_DOMAIN,
multipleInstances: true,
streamingUpload: process.env.COMPANION_STREAMING_UPLOAD === 'true',
maxFileSize: process.env.COMPANION_MAX_FILE_SIZE ? parseInt(process.env.COMPANION_MAX_FILE_SIZE, 10) : undefined,
chunkSize: process.env.COMPANION_CHUNK_SIZE ? parseInt(process.env.COMPANION_CHUNK_SIZE, 10) : undefined,
}
}
/**
* Tries to read the secret from a file if the according environment variable is set.
* Otherwise it falls back to the standard secret environment variable.
*
* @param {string} baseEnvVar
*
* @returns {string}
*/
const getSecret = (baseEnvVar) => {
const secretFile = process.env[`${baseEnvVar}_FILE`]
return secretFile
? fs.readFileSync(secretFile).toString()
: process.env[baseEnvVar]
}
/**
* Auto-generates server secret
*
* @returns {string}
*/
const generateSecret = () => {
logger.warn('auto-generating server secret because none was specified', 'startup.secret')
return crypto.randomBytes(64).toString('hex')
}
/**
* Loads the config from a file and returns it as an object
*
* @returns {object}
*/
const getConfigFromFile = () => {
const path = getConfigPath()
if (!path) return {}
const rawdata = fs.readFileSync(getConfigPath())
// @ts-ignore
return JSON.parse(rawdata)
}
/**
* Returns the config path specified via cli arguments
*
* @returns {string}
*/
const getConfigPath = () => {
let configPath
for (let i = process.argv.length - 1; i >= 0; i--) {<|endoftext|> |
javascript | <fim-prefix>const Promise = require('bluebird');
const {expect} = require('chai');
const sinon = require('sinon');
const PassiveConnector = require('../../../src/connector/passive');
const CMD = 'EPSV';
describe(CMD, function () {
let sandbox;
const mockClient = {
reply: () => Promise.resolve()
};
const cmdFn = require(`../../../src/commands/registration/${CMD.toLowerCase()}`).handler.bind(mockClient);
beforeEach(() => {
sandbox = sinon.sandbox.create().usingPromise(Promise);
sandbox.stub(mockClient, 'reply').resolves();
sandbox.stub(PassiveConnector.prototype, 'setupServer').resolves({
address: () => ({port: 12345})
});
});
afterEach(() => {
sandbox.restore();
});
it('// successful IPv4', () => {
// BUG: CWE-918 Server-Side Request Forgery (SSRF)
// return cmdFn()
// FIXED:
<fim-middle> return cmdFn({})
.then(() => {
const [code, message] = mockClient.reply.args[0];
expect(code).to.equal(229);
expect(message).to.equal('EPSV OK (|||12345|)');
});
});
})<fix-suffix>;
<|endoftext|> |
javascript | <fim-prefix>y
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* EspoCRM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with EspoCRM. If not, see http://www.gnu.org/licenses/.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU General Public License version 3.
*
* In accordance with Section 7(b) of the GNU General Public License version 3,
* these Appropriate Legal Notices must retain the display of the "EspoCRM" word.
************************************************************************/
Espo.define('views/notification/items/assign', 'views/notification/items/base', function (Dep) {
return Dep.extend({
messageName: 'assign',
template: 'notification/items/assign',
setup: function () {
var data = this.model.get('data') || {};
this.userId = data.userId;
this.messageData['entityType'] = Espo.Utils.upperCaseFirst((this.translate(data.entityType, 'scopeNames') || '').toLowerCase());
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// this.messageData['entity'] = '<a href="#' + data.entityType + '/view/' + data.entityId + '">' + data.entityName + '</a>';
// FIXED:
<fim-middle> this.messageData['entity'] = '<a href="#' + this.getHelper().escapeString(data.entityType) + '/view/' + this.getHelper().escapeString(data.entityId) + '">' + this.getHelper().escapeString(<fix-suffix>data.entityName) + '</a>';
this.createMessage();
},
});
});
<|endoftext|> |
javascript | <fim-prefix><fim-middle>(Prism) {
// Functions to construct regular expressions
// simple form
// e.g. (interactive ... or (interactive)
function simple_form(name) {
return RegExp('(\\()' + name + '(?=[\\s\\)])');
}
<fix-suffix>// booleans and numbers
function primitive(pattern) {
return RegExp('([\\s([])' + pattern + '(?=[\\s)])');
}
// Patterns in regular expressions
// Symbol name. See https://www.gnu.org/software/emacs/manual/html_node/elisp/Symbol-Type.html
// & and : are excluded as they are usually used for special purposes
var symbol = '[-+*/_~!@$%^=<>{}\\w]+';
// symbol starting with & used in function arguments
var marker = '&' + symbol;
// Open parenthesis for look-behind
var par = '(\\()';
var endpar = '(?=\\))';
// End the pattern with look-ahead space
var space = '(?=\\s)';
var language = {
// Three or four semicolons are considered a heading.
// See https://www.gnu.org/software/emacs/manual/html_node/elisp/Comment-Tips.html
heading: {
pattern: /;;;.*/,
alias: ['comment', 'title']
},
comment: /;.*/,
string: {
pattern: /"(?:[^"\\]|\\.)*"/,
greedy: true,
inside: {
argument: /[-A-Z]+(?=[.,\s])/,
symbol: RegExp('`' + symbol + "'")
}
},
'quoted-symbol': {
pattern: RegExp("#?'" + symbol),
alias: ['variable', 'symbol']
},
'lisp-property': {
pattern: RegExp(':' + symbol),
alias: 'property'
},
splice: {
pattern: RegExp(',@?' + symbol),
alias: ['symbol', 'variable']
},
keyword: [
{
pattern: RegExp(
par +
'(?:(?:lexical-)?let\\*?|(?:cl-)?letf|if|when|while|unless|cons|cl-loop|and|or|not|cond|setq|error|message|null|require|provide|use-package)' +
space
),
lookbehind: true
<|endoftext|> |
javascript | <fim-prefix>e) {
var parentNode = newResponse;
if (! Ext.isString(node.name)) {
parentNode.push(node);
return;
}
// Get folder name to final container
var parts = Ext.isString(node.name) ? node.name.split("/") : [''];
var containerName = parts[parts.length-1];
// Remove first "" and last item because they don't belong to the folder names
// This could be "" if the name starts with a /
if (parts[0] == "") {
parts.shift();
}
parts.pop();
Ext.each(parts, function (part, idx) {
var child = this.findNodeByName(part, parentNode);
if (! child) {
var child = {
'name': part,
'id': part,
'children': [],
'leaf': false,
'editable': false,
'draggable': false,
'allowDrag': false,
'allowDrop': false,
'singleClickExpand': true,
'listeners': {'beforeclick' : function(n,e) {n.toggle(); return false}}
};
parentNode.push(child);
}
parentNode = child.children;
}, this);
node.longName = node.name;
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// node.text = node.name = Ext.util.Format.htmlEncode(containerName);
// FIXED:
<fim-middle> node.text = node.name = containerName;
parentNode.push(node);
}, this);
response.responseData = newResponse;
return Tine.widgets.tree.Loader.supercla<fix-suffix>ss.processResponse.apply(this, arguments);
},
/**
* Search for a node and return if exists
*
* @param {string} name
* @param {object} nodes
* @return {mixed} node
*/
findNodeByName: function (name, nodes) {
var ret = false;
Ext.each(nodes, function (node, idx) {
if (node && node.name && node.name == name && Ext.isArray(node.children)) {
ret = node;
}
}, this);
return ret;
}
});
<|endoftext|> |
javascript | <fim-prefix><fim-middle>Download plugin script
*
* @licstart The following is the entire license notice for the
* JavaScript code in this file.
*
* Copyright (c) 2013-2014, The Roundcube Dev Team
*
* The JavaScript c<fix-suffix>ode in this page is free software: you can redistribute it
* and/or modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation, either version 3 of
* the License, or (at your option) any later version.
*
* @licend The above is the entire license notice
* for the JavaScript code in this file.
*/
window.rcmail && rcmail.addEventListener('init', function(evt) {
// register additional actions
rcmail.register_command('download-eml', function() { rcmail_zipdownload('eml'); });
rcmail.register_command('download-mbox', function() { rcmail_zipdownload('mbox'); });
rcmail.register_command('download-maildir', function() { rcmail_zipdownload('maildir'); });
// commands status
rcmail.message_list && rcmail.message_list.addEventListener('select', function(list) {
var selected = list.get_selection().length;
rcmail.enable_command('download', selected > 0);
rcmail.enable_command('download-eml', selected == 1);
rcmail.enable_command('download-mbox', 'download-maildir', selected > 1);
});
// hook before default download action
rcmail.addEventListener('beforedownload', rcmail_zipdownload_menu);
// find and modify default download link/button
$.each(rcmail.buttons['download'] || [], function() {
var link = $('#' + this.id),
span = $('span', link);
if (!span.length) {
span = $('<span>');
link.html('').append(sp<|endoftext|> |
javascript | <fim-prefix> response.participants) {
var p = response.participants[i];
participants[p.username] = escapeXmlTags(p.display ? p.display : p.username);
if(p.username !== myid && $('#rp' + p.username).length === 0) {
// Add to the participants list
$('#list').append('<li id="rp' + p.username + '" class="list-group-item">' + participants[p.username] + '</li>');
$('#rp' + p.username).css('cursor', 'pointer').click(function() {
var username = $(this).attr('id').split("rp")[1];
sendPrivateMsg(username);
});
}
$('#chatroom').append('<p style="color: green;">[' + getDateString() + '] <i>' + participants[p.username] + ' joined</i></p>');
$('#chatroom').get(0).scrollTop = $('#chatroom').get(0).scrollHeight;
}
}
};
textroom.data({
text: JSON.stringify(register),
error: function(reason) {
bootbox.alert(reason);
$('#username').removeAttr('disabled').val("");
$('#register').removeAttr('disabled').click(registerUsername);
}
});
}
}
function sendPrivateMsg(username) {
var display = participants[username];
if(!display)
return;
bootbox.prompt("Private message to " + display, function(result) {
if(result && result !== "") {
var message = {
textroom: "message",
transaction: randomString(12),
room: myroom,
to: username,
text: result
};
textroom.data({
text: JSON.stringify(message),
error: function(reason) { bootbox.alert(reason); },
success: function() {
// BUG: CWE-79 Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
// $('#chatroom').append('<p style="color: purple;">[' + getDateString() + '] <b>[whisper to ' + display + ']</b> ' + result);
// FIXED:
<fim-middle> $('#chatroom').append('<p style="color: purple;">[' + getDateString() + '] <b>[whisper to ' + display + ']</b> ' + escapeXmlTags(result));
$('#chatroom').get(0).scrollTop = $('#chatroom').ge<fix-suffix>t(0).scrollHeight;
}
});
}
});
return;
}
function sendData() {
var data = $('#datasend').val();
if(data === "") {
bootbox.alert('Insert a message to send on the DataChannel');
return;
}
var message = {
textroom: "message",
transaction: randomString(12),
room: myroom,
text: data,
};
// Note: messages are always acknowledged by default. This means that you'll
// always receive a confirmation back that the message has been received by the
// server and forwarded to the recipients. If you do not want this to happen,
// just add an ack:false property to the message above, and server won't send
// you a response (meaning you just have to hope it succeeded).
textroom.data({
text: JSON.stringify(message),
error: function(reason) { bootbox.alert(reason); },
success: function() { $('#datasend').val(''); }
});
}
// Helper to format times
function getDateString(jsonDate) {
var when = new Date();
if(jsonDate) {
when = new Date(Date.parse(jsonDate));
}
var dateString =
("0" + when.getUTCHours()).slice(-2) + ":" +
("0" + when.getUTCMinutes()).slice(-2) + ":" +
("0" + when.getUTCSeconds()).slice(-2);
return dateString;
}
// Just an helper to generate random usernames
function randomString(len, charSet) {
charSet = charSet || 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
var randomString = '';
for (var i = 0; i < len; i++) {
var randomPoz = Math.floor(Math.random() * charSet.length);
randomS<|endoftext|> |
javascript | <fim-prefix>enerateSegmentedPathFunction(':', 'decodeUrnPathSegment');
URI.recodePath = generateSegmentedPathFunction('/', 'encodePathSegment', 'decode');
URI.recodeUrnPath = generateSegmentedPathFunction(':', 'encodeUrnPathSegment', 'decode');
URI.encodeReserved = generateAccessor('reserved', 'encode');
URI.parse = function(string, parts) {
var pos;
if (!parts) {
parts = {
preventInvalidHostname: URI.preventInvalidHostname
};
}
// [protocol"://"[username[":"password]"@"]hostname[":"port]"/"?][path]["?"querystring]["#"fragment]
// extract fragment
pos = string.indexOf('#');
if (pos > -1) {
// escaping?
parts.fragment = string.substring(pos + 1) || null;
string = string.substring(0, pos);
}
// extract query
pos = string.indexOf('?');
if (pos > -1) {
// escaping?
parts.query = string.substring(pos + 1) || null;
string = string.substring(0, pos);
}
// extract protocol
if (string.substring(0, 2) === '//') {
// relative-scheme
parts.protocol = null;
string = string.substring(2);
// extract "user:pass@host:port"
string = URI.parseAuthority(string, parts);
} else {
pos = string.indexOf(':');
if (pos > -1) {
parts.protocol = string.substring(0, pos) || null;
if (parts.protocol && !parts.protocol.match(URI.protocol_expression)) {
// : may be within the path
parts.protocol = undefined;
// BUG: NVD-CWE-noinfo Insufficient Information
// } else if (string.substring(pos + 1, pos + 3) === '//') {
// FIXED:
<fim-middle> } else if (string.substring(pos + 1, pos + 3).replace(/\\/g, '/') === '//') {
string = string.substring(pos + 3);
// extract "user:pass@host:port"
string = URI.p<fix-suffix>arseAuthority(string, parts);
} else {
string = string.substring(pos + 1);
parts.urn = true;
}
}
}
// what's left must be the path
parts.path = string;
// and we're done
return parts;
};
URI.parseHost = function(string, parts) {
if (!string) {
string = '';
}
// Copy chrome, IE, opera backslash-handling behavior.
// Back slashes before the query string get converted to forward slashes
// See: https://github.com/joyent/node/blob/386fd24f49b0e9d1a8a076592a404168faeecc34/lib/url.js#L115-L124
// See: https://code.google.com/p/chromium/issues/detail?id=25916
// https://github.com/medialize/URI.js/pull/233
string = string.replace(/\\/g, '/');
// extract host:port
var pos = string.indexOf('/');
var bracketPos;
var t;
if (pos === -1) {
pos = string.length;
}
if (string.charAt(0) === '[') {
// IPv6 host - http://tools.ietf.org/html/draft-ietf-6man-text-addr-representation-04#section-6
// I claim most client software breaks on IPv6 anyways. To simplify things, URI only accepts
// IPv6+port in the format [2001:db8::1]:80 (for the time being)
bracketPos = string.indexOf(']');
parts.hostname = string.substring(1, bracketPos) || null;
parts.port = string.substring(bracketPos + 2, pos) || null;
if (parts.port === '/') {
parts.port = null;
}
} else {
var firstColon = string.indexOf(':')<|endoftext|> |