Merge branch 'staging' into soon

pull/1/head
ansuz 4 years ago
commit 39afc64ba7

@ -5,14 +5,53 @@
* reminders in calendars
* import/export
* include LICENSE for ical.js
* translations
* out of BETA
* available from user admin menu
* mobile styles fixed
* import calendars from URL
* anonymous viewing of calendars from URL
* settings
* use a specific version of bootstrap-tokenfield in bower.json
* don't create readmes
* support displaying a roadmap in static pages' footer
* adjust threshold for whiteboard file size limit to better match user expectation (file size instead of base64 size)
* XXX still incorrect?
* FLOC OFF GOOGLE header
* opt out of Google's FLoC Network
* /report/ page
* broadcast channel included in pin list
* fix package-lock to use server update
* code app present mode fix
* sheets
* lock sheets faster when applying checkpoints
* guard against undefined checkpoints
* don't spam users with prompts to checkpoints when they can't
* warn users when their browser doesn't support import/export so they don't email us
* check that WebAssembly exists
* decrees
* SET_ADMIN_EMAIL
* SET_SUPPORT_MAILBOX
* Add DAPSI to our sponsor list
* checkup
* check for duplicate or incorrect headers
* check for missing adminEmail
* XXX make sure this is present on prod
* save rendered markmap, mathjax, and mermaid as images
* guard against incorrect iPhone behaviour that broke the ability to toggle between grid and list mode
* new issue template
* registration
* additional validation for block uploads
* ability to close registration via the admin panel
* handle an silent error
* add "store in drive" to app toolbar's file menu
* XXX check sheets and polls?
* not in sheets
* not in polls
* XXX CryptGet changes?
* onCacheReady
* guard against input that crashes diffDOM
* https://github.com/xwiki-labs/cryptpad/issues/620
# 4.4.0

Binary file not shown.

After

Width:  |  Height:  |  Size: 202 KiB

@ -392,7 +392,7 @@ define([
// send an RPC to store the block which you created.
console.log("initializing rpc interface");
Pinpad.create(RT.network, RT.proxy, waitFor(function (e, _rpc) {
Pinpad.create(RT.network, Block.keysToRPCFormat(res.opt.blockKeys), waitFor(function (e, _rpc) {
if (e) {
waitFor.abort();
console.error(e); // INVALID_KEYS
@ -414,7 +414,10 @@ define([
var blockRequest = Block.serialize(JSON.stringify(toPublish), res.opt.blockKeys);
rpc.writeLoginBlock(blockRequest, waitFor(function (e) {
if (e) { return void console.error(e); }
if (e) {
console.error(e);
return void cb(e);
}
console.log("blockInfo available at:", blockHash);
LocalStore.setBlockHash(blockHash);
@ -531,6 +534,9 @@ define([
});
});
break;
case 'E_RESTRICTED':
UI.errorLoadingScreen(Messages.register_registrationIsClosed);
break;
default: // UNHANDLED ERROR
hashing = false;
UI.errorLoadingScreen(Messages.login_unhandledError);

@ -4,7 +4,8 @@ define([
'/customize/application_config.js',
'/customize/messages.js',
'jquery',
], function (h, Language, AppConfig, Msg, $) {
'/api/config',
], function (h, Language, AppConfig, Msg, $, ApiConfig) {
var Pages = {};
Pages.setHTML = function (e, html) {
@ -93,13 +94,15 @@ define([
var imprintUrl = AppConfig.imprint && (typeof(AppConfig.imprint) === "boolean" ?
'/imprint.html' : AppConfig.imprint);
Pages.versionString = "v4.4.0";
Pages.versionString = "v4.5.0";
// used for the about menu
Pages.imprintLink = AppConfig.imprint ? footLink(imprintUrl, 'imprint') : undefined;
Pages.privacyLink = footLink(AppConfig.privacy, 'privacy');
Pages.githubLink = footLink('https://github.com/xwiki-labs/cryptpad', null, 'GitHub');
Pages.docsLink = footLink('https://docs.cryptpad.fr', 'docs_link');
Pages.roadmapLink = footLink(AppConfig.roadmap, 'footer_roadmap');
Pages.infopageFooter = function () {
var terms = footLink('/terms.html', 'footer_tos'); // FIXME this should be configurable like the other legal pages
@ -139,6 +142,7 @@ define([
footLink('/contact.html', 'contact'),
footLink('https://github.com/xwiki-labs/cryptpad/wiki/Contributors', 'footer_team'),
footLink('http://www.xwiki.com', null, 'XWiki SAS'),
Pages.roadmapLink,
]),
legalFooter,
])
@ -153,10 +157,16 @@ define([
Pages.infopageTopbar = function () {
var rightLinks;
var username = window.localStorage.getItem('User_name');
var registerLink;
if (!ApiConfig.restrictRegistration) {
registerLink = h('a.nav-item.nav-link.cp-register-btn', { href: '/register/'}, Msg.login_register);
}
if (username === null) {
rightLinks = [
h('a.nav-item.nav-link.cp-login-btn', { href: '/login/'}, Msg.login_login),
h('a.nav-item.nav-link.cp-register-btn', { href: '/register/'}, Msg.login_register)
registerLink,
];
} else {
rightLinks = h('a.nav-item.nav-link.cp-user-btn', { href: '/drive/' }, [

@ -7,8 +7,13 @@ define([
], function (Config, h, Msg, Pages, LocalStore) {
return function () {
var adminEmail = Config.adminEmail && Config.adminEmail !== 'i.did.not.read.my.config@cryptpad.fr';
var developerEmail = "contact@cryptpad.fr";
var adminEmail = Config.adminEmail && [
'i.did.not.read.my.config@cryptpad.fr',
developerEmail
].indexOf(Config.adminEmail) === -1;
var adminMailbox = Config.supportMailbox && LocalStore.isLoggedIn();
return h('div#cp-main', [
Pages.infopageTopbar(),
h('div.container.cp-container', [
@ -110,7 +115,7 @@ define([
)
),
h('div.col-12.col-sm-6.col-md-3.col-lg-3',
h('a.card', {href : "mailto:contact@cryptpad.fr"},
h('a.card', {href : "mailto:" + developerEmail},
h('div.card-body',
h('p', [
h('img', {

@ -146,7 +146,7 @@ define([
]),
]);
var availableFeatures =
(Config.allowSubscriptions && accounts.upgradeURL) ?
(Config.allowSubscriptions && accounts.upgradeURL && !Config.restrictRegistration) ?
[anonymousFeatures, registeredFeatures, premiumFeatures] :
[anonymousFeatures, registeredFeatures];

@ -2,8 +2,9 @@ define([
'/common/hyperscript.js',
'/common/common-interface.js',
'/customize/messages.js',
'/customize/pages.js'
], function (h, UI, Msg, Pages) {
'/customize/pages.js',
'/api/config',
], function (h, UI, Msg, Pages, Config) {
return function () {
return [h('div#cp-main', [
Pages.infopageTopbar(),
@ -32,7 +33,10 @@ define([
]),
h('div.extra', [
h('button.login', Msg.login_login),
(Config.restrictRegistration?
undefined:
h('button#register.cp-secondary', Msg.login_register)
)
])
]),
h('div.col-md-3')

@ -16,10 +16,29 @@ define([
tabindex: '-1',
});
return [h('div#cp-main', [
var frame = function (content) {
return [
h('div#cp-main', [
Pages.infopageTopbar(),
h('div.container.cp-container', [
h('div.row.cp-page-title', h('h1', Msg.register_header)),
//h('div.row.cp-register-det', content),
].concat(content)),
]),
Pages.infopageFooter(),
];
};
if (Config.restrictRegistration) {
return frame([
h('div.cp-restricted-registration', [
h('p', Msg.register_registrationIsClosed),
])
]);
}
return frame([
h('div.row.cp-register-det', [
h('div#data.hidden.col-md-6', [
h('h2', Msg.register_notes_title),
@ -59,11 +78,8 @@ define([
h('button#register', Msg.login_register)
])
]),
]),
]),
Pages.infopageFooter(),
])];
])
]);
};
});

@ -89,6 +89,8 @@ define([
'https://www.mozilla.org/en-US/moss/'),
logoLink('NGI Trust logo', '/customize/images/logo_ngi_trust.png',
'https://www.ngi.eu/ngi-projects/ngi-trust/'),
logoLink('NGI DAPSI LOGO', '/customize/images/logo_ngi_dapsi.png',
'https://dapsi.ngi.eu/'),
]),
]),
h('div.row.cp-page-section', [

@ -423,3 +423,6 @@
// Calendar
@cp_calendar-border: @cryptpad_color_grey_600;
@cp_calendar-now: @cryptpad_color_brand_300;
@cp_calendar-now-fg: @cryptpad_color_grey_800;

@ -423,3 +423,5 @@
// Calendar
@cp_calendar-border: @cryptpad_color_grey_300;
@cp_calendar-now: @cryptpad_color_brand;
@cp_calendar-now-fg: @cryptpad_color_grey_200;

@ -1,6 +1,12 @@
.cursor_main() {
// CodeMirror
.cp-codemirror-cursor {
&:before {
content: "";
display: inline-block;
}
cursor: default;
background-color: red;
background-clip: padding-box;
@ -8,8 +14,8 @@
border: 2px solid red;
border-right-color: transparent !important;
border-left-color: transparent !important;
margin-left: -3px;
margin-right: -3px;
display: inline-block;
margin: -2px -3px;
}
.cp-codemirror-selection {
background-color: rgba(255,0,0,0.3);

@ -606,7 +606,7 @@
}
}
.cp-app-drive-content-list {
div.cp-app-drive-content-list {
.cp-app-drive-element-grid {
display: none;
}
@ -896,7 +896,13 @@
.cp-toolbar-bottom {
.cp-toolbar-bottom-right {
.fa-history { order: 50; }
.fa-list, .fa-th-large { order: 25; }
// .fa-list, .fa-th-large,
.cp-app-drive-viewmode-button {
order: 25;
i {
margin-right: 0;
}
}
#cp-app-drive-toolbar-context-mobile, #cp-app-drive-toolbar-contextbuttons { order: 0; }
#cp-app-drive-toolbar-context-mobile {
.fa { margin: 0 !important; }

@ -122,7 +122,7 @@
&.small {
line-height: initial;
padding: 5px;
height: auto;
height: auto !important;
}
&:hover, &:not(:disabled):not(.disabled):active, &:focus {

@ -23,7 +23,7 @@
align-items: center;
padding: 0 5px;
color: @cp_dropdown-fg;
&.preview {
&.preview:not(.fa-calendar) {
color: @cryptpad_color_red;
}
}

@ -52,6 +52,9 @@
}
}
.cp-restricted-registration {
text-align: center !important;
}
.cp-register-det {
#data {

@ -50,7 +50,6 @@ $(function () {
} else if (/^\/login\//.test(pathname)) {
require([ '/login/main.js' ], function () {});
} else if (/^\/($|^\/index\.html$)/.test(pathname)) {
// TODO use different top bar
require([ '/customize/main.js', ], function () {});
} else {
require([ '/customize/main.js', ], function () {});

@ -86,30 +86,103 @@ var createLoginBlockPath = function (Env, publicKey) { // FIXME BLOCKS
return Path.join(Env.paths.block, safeKey.slice(0, 2), safeKey);
};
Block.writeLoginBlock = function (Env, safeKey, msg, cb) { // FIXME BLOCKS
Block.validateAncestorProof = function (Env, proof, _cb) {
var cb = Util.once(Util.mkAsync(_cb));
/* prove that you own an existing block by signing for its publicKey */
try {
var parsed = JSON.parse(proof);
var pub = parsed[0];
var u8_pub = Nacl.util.decodeBase64(pub);
var sig = parsed[1];
var u8_sig = Nacl.util.decodeBase64(sig);
var valid = false;
nThen(function (w) {
valid = Nacl.sign.detached.verify(u8_pub, u8_sig, u8_pub);
if (!valid) {
w.abort();
return void cb('E_INVALID_ANCESTOR_PROOF');
}
// else fall through to next step
}).nThen(function (w) {
var path = createLoginBlockPath(Env, pub);
Fs.access(path, Fs.constants.F_OK, w(function (err) {
if (!err) { return; }
w.abort(); // else
return void cb("E_MISSING_ANCESTOR");
}));
}).nThen(function () {
cb(void 0, pub);
});
} catch (err) {
return void cb(err);
}
};
Block.writeLoginBlock = function (Env, safeKey, msg, _cb) { // FIXME BLOCKS
var cb = Util.once(Util.mkAsync(_cb));
//console.log(msg);
var publicKey = msg[0];
var signature = msg[1];
var block = msg[2];
var registrationProof = msg[3];
var previousKey;
validateLoginBlock(Env, publicKey, signature, block, function (e, validatedBlock) {
if (e) { return void cb(e); }
if (!(validatedBlock instanceof Uint8Array)) { return void cb('E_INVALID_BLOCK'); }
var validatedBlock, parsed, path;
nThen(function (w) {
if (Util.escapeKeyCharacters(publicKey) !== safeKey) {
w.abort();
return void cb("INCORRECT_KEY");
}
}).nThen(function (w) {
if (!Env.restrictRegistration) { return; }
if (!registrationProof) {
// we allow users with existing blocks to create new ones
// call back with error if registration is restricted and no proof of an existing block was provided
w.abort();
Env.Log.info("BLOCK_REJECTED_REGISTRATION", {
safeKey: safeKey,
publicKey: publicKey,
});
return cb("E_RESTRICTED");
}
Env.validateAncestorProof(registrationProof, w(function (err, provenKey) {
if (err || !provenKey) { // double check that a key was validated
w.abort();
Env.Log.warn('BLOCK_REJECTED_INVALID_ANCESTOR', {
error: err,
});
return void cb("E_RESTRICTED");
}
previousKey = provenKey;
}));
}).nThen(function (w) {
validateLoginBlock(Env, publicKey, signature, block, w(function (e, _validatedBlock) {
if (e) {
w.abort();
return void cb(e);
}
if (!(_validatedBlock instanceof Uint8Array)) {
w.abort();
return void cb('E_INVALID_BLOCK');
}
validatedBlock = _validatedBlock;
// derive the filepath
var path = createLoginBlockPath(Env, publicKey);
path = createLoginBlockPath(Env, publicKey);
// make sure the path is valid
if (typeof(path) !== 'string') {
return void cb('E_INVALID_BLOCK_PATH');
}
var parsed = Path.parse(path);
parsed = Path.parse(path);
if (!parsed || typeof(parsed.dir) !== 'string') {
w.abort();
return void cb("E_INVALID_BLOCK_PATH_2");
}
nThen(function (w) {
}));
}).nThen(function (w) {
// make sure the path to the file exists
Fse.mkdirp(parsed.dir, w(function (e) {
if (e) {
@ -119,14 +192,16 @@ Block.writeLoginBlock = function (Env, safeKey, msg, cb) { // FIXME BLOCKS
}));
}).nThen(function () {
// actually write the block
// flow is dumb and I need to guard against this which will never happen
/*:: if (typeof(validatedBlock) === 'undefined') { throw new Error('should never happen'); } */
/*:: if (typeof(path) === 'undefined') { throw new Error('should never happen'); } */
Fs.writeFile(path, Buffer.from(validatedBlock), { encoding: "binary", }, function (err) {
if (err) { return void cb(err); }
cb();
Env.Log.info('BLOCK_WRITE_BY_OWNER', {
safeKey: safeKey,
blockId: publicKey,
isChange: Boolean(registrationProof),
previousKey: previousKey,
path: path,
});
cb();
});
});
};
@ -146,6 +221,12 @@ Block.removeLoginBlock = function (Env, safeKey, msg, cb) { // FIXME BLOCKS
var signature = msg[1];
var block = Nacl.util.decodeUTF8('DELETE_BLOCK'); // clients and the server will have to agree on this constant
nThen(function (w) {
if (Util.escapeKeyCharacters(publicKey) !== safeKey) {
w.abort();
return void cb("INCORRECT_KEY");
}
}).nThen(function () {
validateLoginBlock(Env, publicKey, signature, block, function (e /*::, validatedBlock */) {
if (e) { return void cb(e); }
// derive the filepath
@ -168,5 +249,6 @@ Block.removeLoginBlock = function (Env, safeKey, msg, cb) { // FIXME BLOCKS
cb();
});
});
});
};

@ -13,6 +13,10 @@ Core.isValidId = function (chan) {
[32, 33, 48].indexOf(chan.length) > -1;
};
Core.isValidPublicKey = function (owner) {
return typeof(owner) === 'string' && owner.length === 44;
};
var makeToken = Core.makeToken = function () {
return Number(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER))
.toString(16);

@ -1,4 +1,5 @@
var Decrees = module.exports;
var Core = require("./commands/core");
/* Admin decrees which modify global server state
@ -29,6 +30,10 @@ SET_LAST_BROADCAST_HASH
SET_SURVEY_URL
SET_MAINTENANCE
// EASIER CONFIG
SET_ADMIN_EMAIL
SET_SUPPORT_MAILBOX
NOT IMPLEMENTED:
// RESTRICTED REGISTRATION
@ -37,9 +42,11 @@ REVOKE_INVITE
REDEEM_INVITE
// 2.0
Env.adminEmail
Env.supportMailbox
Env.DEV_MODE || Env.FRESH_MODE,
ADD_ADMIN_KEY
RM_ADMIN_KEY
*/
var commands = {};
@ -88,6 +95,20 @@ var isNonNegativeNumber = function (n) {
};
*/
var default_validator = function () { return true; };
var makeGenericSetter = function (attr, validator) {
validator = validator || default_validator;
return function (Env, args) {
if (!validator(args)) {
throw new Error("INVALID_ARGS");
}
var value = args[0];
if (value === Env[attr]) { return false; }
Env[attr] = value;
return true;
};
};
var isInteger = function (n) {
return !(typeof(n) !== 'number' || isNaN(n) || (n % 1) !== 0);
};
@ -97,15 +118,7 @@ var args_isInteger = function (args) {
};
var makeIntegerSetter = function (attr) {
return function (Env, args) {
if (!args_isInteger(args)) {
throw new Error('INVALID_ARGS');
}
var integer = args[0];
if (integer === Env[attr]) { return false; }
Env[attr] = integer;
return true;
};
return makeGenericSetter(attr, args_isInteger);
};
// CryptPad_AsyncStore.rpc.send('ADMIN', [ 'ADMIN_DECREE', ['SET_MAX_UPLOAD_SIZE', [50 * 1024 * 1024]]], console.log)
@ -130,6 +143,14 @@ var args_isString = function (args) {
return Array.isArray(args) && typeof(args[0]) === "string";
};
// CryptPad_AsyncStore.rpc.send('ADMIN', [ 'ADMIN_DECREE', ['SET_ADMIN_EMAIL', ['admin@website.tld']]], console.log)
commands.SET_ADMIN_EMAIL = makeGenericSetter('adminEmail', args_isString);
// CryptPad_AsyncStore.rpc.send('ADMIN', [ 'ADMIN_DECREE', ['SET_SUPPORT_MAILBOX', ["Tdz6+fE9N9XXBY93rW5qeNa/k27yd40c0vq7EJyt7jA="]]], console.log)
commands.SET_SUPPORT_MAILBOX = makeGenericSetter('supportMailbox', function (args) {
return args_isString(args) && Core.isValidPublicKey(args[0]);
});
// Maintenance: Empty string or an object with a start and end time
var isNumber = function (value) {
return typeof(value) === "number" && !isNaN(value);

@ -89,6 +89,11 @@ module.exports.create = function (config) {
}
},
/* FIXME restrictRegistration is initialized as false and then overridden by admin decree
There is a narrow window in which someone could register before the server updates this value.
See also the cached 'restrictRegistration' value in server.js#serveConfig
*/
restrictRegistration: false,
allowSubscriptions: config.allowSubscriptions === true,
blockDailyCheck: config.blockDailyCheck === true,

@ -158,6 +158,7 @@ module.exports.create = function (Env, cb) {
pinPath: Env.paths.pin,
filePath: Env.paths.data,
archivePath: Env.paths.archive,
blockPath: Env.paths.block,
inactiveTime: Env.inactiveTime,
archiveRetentionTime: Env.archiveRetentionTime,

@ -1,4 +1,5 @@
var Meta = module.exports;
var Core = require("./commands/core");
var deduplicate = require("./common-util").deduplicateString;
@ -35,9 +36,7 @@ the owners field is guaranteed to exist.
var commands = {};
var isValidPublicKey = function (owner) {
return typeof(owner) === 'string' && owner.length === 44;
};
var isValidPublicKey = Core.isValidPublicKey;
// isValidPublicKey is a better indication of what the above function does
// I'm preserving this function name in case we ever want to expand its

@ -295,7 +295,7 @@ var owned_upload_complete = function (Env, safeKey, id, cb) {
// removeBlob
var remove = function (Env, blobId, cb) {
var blobPath = makeBlobPath(Env, blobId);
Fs.unlink(blobPath, cb); // TODO COLDSTORAGE
Fs.unlink(blobPath, cb);
};
// removeProof

@ -4,6 +4,7 @@
const HK = require("../hk-util");
const Store = require("../storage/file");
const BlobStore = require("../storage/blob");
const Block = require("../commands/block");
const Util = require("../common-util");
const nThen = require("nthen");
const Meta = require("../metadata");
@ -47,6 +48,7 @@ const init = function (config, _cb) {
Env.paths = {
pin: config.pinPath,
block: config.blockPath,
};
Env.inactiveTime = config.inactiveTime;
@ -688,6 +690,10 @@ COMMANDS.HASH_CHANNEL_LIST = function (data, cb) {
cb(void 0, hash);
};
COMMANDS.VALIDATE_ANCESTOR_PROOF = function (data, cb) {
Block.validateAncestorProof(Env, data && data.proof, cb);
};
process.on('message', function (data) {
if (!data || !data.txid || !data.pid) {
return void process.send({

@ -444,6 +444,13 @@ Workers.initialize = function (Env, config, _cb) {
}, cb);
};
Env.validateAncestorProof = function (proof, cb) {
sendCommand({
command: 'VALIDATE_ANCESTOR_PROOF',
proof: proof,
}, cb);
};
cb(void 0);
});
};

2
package-lock.json generated

@ -1,6 +1,6 @@
{
"name": "cryptpad",
"version": "4.4.0",
"version": "4.5.0",
"lockfileVersion": 1,
"requires": true,
"dependencies": {

@ -1,7 +1,7 @@
{
"name": "cryptpad",
"description": "realtime collaborative visual editor with zero knowlege server",
"version": "4.4.0",
"version": "4.5.0",
"license": "AGPL-3.0+",
"repository": {
"type": "git",

@ -111,7 +111,8 @@ var setHeaders = (function () {
"Cross-Origin-Embedder-Policy": 'require-corp',
});
if (Env.NO_SANDBOX) {
if (Env.NO_SANDBOX) { // handles correct configuration for local development
// https://stackoverflow.com/questions/11531121/add-duplicate-http-response-headers-in-nodejs
applyHeaderMap(res, {
"Cross-Origin-Resource-Policy": 'cross-origin',
});
@ -120,11 +121,13 @@ var setHeaders = (function () {
// Don't set CSP headers on /api/config because they aren't necessary and they cause problems
// when duplicated by NGINX in production environments
if (/^\/api\/(broadcast|config)/.test(req.url)) {
if (!Env.NO_SANDBOX) {
/*
if (Env.NO_SANDBOX) {
applyHeaderMap(res, {
"Cross-Origin-Resource-Policy": 'cross-origin',
});
}
*/
return;
}
applyHeaderMap(res, {
@ -276,6 +279,7 @@ var serveConfig = makeRouteCache(function (host) {
defaultStorageLimit: Env.defaultStorageLimit,
maxUploadSize: Env.maxUploadSize,
premiumUploadSize: Env.premiumUploadSize,
restrictRegistration: Env.restrictRegistration, // FIXME see the race condition in env.js
}, null, '\t'),
'obj.httpSafeOrigin = ' + (function () {
if (config.httpSafeOrigin) { return '"' + config.httpSafeOrigin + '"'; }

@ -53,7 +53,7 @@ define([
'cp-admin-update-limit',
'cp-admin-archive',
'cp-admin-unarchive',
// 'cp-admin-registration',
'cp-admin-registration',
],
'quota': [ // Msg.admin_cat_quota
'cp-admin-defaultlimit',
@ -253,36 +253,32 @@ define([
create['registration'] = function () {
var key = 'registration';
var $div = makeBlock(key, true); // Msg.admin_registrationHint, .admin_registrationTitle, .admin_registrationButton
var $button = $div.find('button');
var $div = makeBlock(key); // Msg.admin_registrationHint, .admin_registrationTitle, .admin_registrationButton
var state = APP.instanceStatus.restrictRegistration;
if (state) {
$button.text(Messages.admin_registrationAllow);
} else {
$button.removeClass('btn-primary').addClass('btn-danger');
}
var called = false;
$div.find('button').click(function () {
called = true;
var $cbox = $(UI.createCheckbox('cp-settings-userfeedback',
Messages.admin_registrationTitle,
state, { label: { class: 'noTitle' } }));
var spinner = UI.makeSpinner($cbox);
var $checkbox = $cbox.find('input').on('change', function() {
spinner.spin();
var val = $checkbox.is(':checked') || false;
$checkbox.attr('disabled', 'disabled');
sFrameChan.query('Q_ADMIN_RPC', {
cmd: 'ADMIN_DECREE',
data: ['RESTRICT_REGISTRATION', [!state]]
data: ['RESTRICT_REGISTRATION', [val]]
}, function (e) {
if (e) { UI.warn(Messages.error); console.error(e); }
APP.updateStatus(function () {
called = false;
spinner.done();
state = APP.instanceStatus.restrictRegistration;
if (state) {
console.log($button);
$button.text(Messages.admin_registrationAllow);
$button.addClass('btn-primary').removeClass('btn-danger');
} else {
$button.text(Messages.admin_registrationButton);
$button.removeClass('btn-primary').addClass('btn-danger');
}
$checkbox[0].checked = state;
$checkbox.removeAttr('disabled');
});
});
});
$cbox.appendTo($div);
return $div;
};

@ -11,6 +11,10 @@
display: flex;
flex-flow: column;
.cp-toolbar-bottom-mid > div {
.cp-small { display: none; }
}
#cp-sidebarlayout-container #cp-sidebarlayout-rightside {
padding: 0;
& > div {
@ -41,25 +45,52 @@
}
}
}
.tui-full-calendar-weekday-filled {
background-color: @cp_dropdown-bg-hover !important;
}
.tui-full-calendar-timegrid-hourmarker-time {
color: @cp_calendar-now !important;
}
.tui-full-calendar-timegrid-hourmarker-line-left, .tui-full-calendar-timegrid-hourmarker-line-today {
border-color: @cp_calendar-now !important;
}
.tui-full-calendar-timegrid-todaymarker {
background-color: @cp_calendar-now !important;
}
.tui-full-calendar-month {
display: flex;
flex-flow: column;
& > div:last-child {
display: flex;
flex-flow: column;
flex: 1;
min-height: 0;
overflow: hidden;
}
.tui-full-calendar-today .tui-full-calendar-weekday-grid-date-decorator {
background-color: @cp_calendar-now !important;
color: @cp_calendar-now-fg !important;
}
.tui-full-calendar-weekday-schedule-time .tui-full-calendar-weekday-schedule-title {
color: @cryptpad_text_col !important; // XXX
color: @cryptpad_text_col !important;
}
.tui-full-calendar-extra-date {
.tui-full-calendar-weekday-grid-date {
color: @cp_sidebar-hint !important; // XXX
color: @cp_sidebar-hint !important;
opacity: 0.5;
}
}
.tui-full-calendar-weekday-grid-date {
color: @cryptpad_text_col !important; // XXX
color: @cryptpad_text_col !important;
}
.tui-full-calendar-month-dayname-item span {
color: @cryptpad_text_col !important; // XXX
color: @cryptpad_text_col !important;
}
}
.tui-full-calendar-dayname * {
color: @cryptpad_text_col !important; // XXX
color: @cryptpad_text_col !important;
}
.tui-full-calendar-month-more {
background-color: @cp_sidebar-right-bg !important;
@ -178,6 +209,57 @@
}
}
.cp-calendar-add-notif {
flex-flow: column;
align-items: baseline !important;
margin: 10px 0;
.cp-notif-label {
color: @cp_sidebar-hint;
margin-right: 20px;
}
* {
font-size: @colortheme_app-font-size;
font-weight: normal;
}
& > div {
display: flex;
}
.cp-calendar-notif-list-container {
margin-bottom: 10px;
}
.cp-calendar-notif-list {
display: flex;
flex-flow: column;
.cp-notif-entry {
margin-bottom: 2px;
.cp-notif-value {
width: 170px;
display: inline-flex;
.cp-before {
flex: 1;
min-width: 0;
}
}
span:not(:last-child) {
margin-right: 5px;
}
}
}
.cp-notif-empty {
display: none;
}
.cp-calendar-notif-list:empty ~ .cp-notif-empty {
display: block;
}
.cp-calendar-notif-form {
align-items: center;
margin-bottom: 20px;
input {
width: 100px;
}
}
}
.cp-calendar-close {
height: auto;
line-height: initial;
@ -203,6 +285,7 @@
justify-content: space-between;
}
.cp-calendar-list {
overflow-y: auto;
.cp-calendar-team {
height: 30px;
.avatar_main(30px);
@ -218,13 +301,21 @@
align-items: center;
justify-content: center;
margin: 5px 0;
&:not(:first-child) {
margin-top: 30px;
}
}
.cp-calendar-entry {
display: flex;
align-items: center;
justify-content: space-between;
padding: 5px;
&:not(.cp-unclickable) {
cursor: pointer;
}
.cp-dropdown-container {
position: initial;
}
&.cp-ghost {
padding: 0;
button {
@ -253,8 +344,27 @@
&.cp-restricted {
color: @cp_drive-header-fg;
}
.cp-calendar-icon {
width: 36px;
display: inline-flex;
height: 36px;
margin: -5px;
align-items: center;
justify-content: center;
}
&.cp-active {
background: @cp_sidebar-left-active;
.cp-calendar-inactive {
display: none;
}
}
&:not(.cp-active) {
.cp-calendar-icon {
background: transparent !important;
}
.cp-calendar-active {
display: none;
}
}
.tools_unselectable();
.cp-calendar-color {
@ -279,5 +389,43 @@
cursor: pointer;
border: 1px solid @cp_forms-border;
}
@media (max-width: @browser_media-medium-screen) {
.cp-calendar-newevent {
i {
margin: 0 !important;
}
span {
display: none;
}
}
.tui-full-calendar-dayname-leftmargin, .tui-full-calendar-timegrid-right {
margin-left: 40px !important;
}
.tui-full-calendar-allday-left, .tui-full-calendar-timegrid-left {
width: 40px !important;
}
.tui-full-calendar-dayname > span {
display: flex;
flex-flow: column;
line-height: 0;
justify-content: center;
align-items: center;
height: 100%;
}
.tui-full-calendar-dayname * {
font-size: 11px;
line-height: initial;
height: auto;
}
.cp-toolbar-bottom-mid > div {
:not(:first-child) {
display: none;
}
:first-child {
display: inline-block;
}
}
}
}

@ -0,0 +1,208 @@
// This file is used when a user tries to export the entire CryptDrive.
// Calendars will be exported using this format instead of plain text.
define([
'/customize/pages.js',
], function (Pages) {
var module = {};
var getICSDate = function (str) {
var date = new Date(str);
var m = date.getUTCMonth() + 1;
var d = date.getUTCDate();
var h = date.getUTCHours();
var min = date.getUTCMinutes();
var year = date.getUTCFullYear().toString();
var month = m < 10 ? "0" + m : m.toString();
var day = d < 10 ? "0" + d : d.toString();
var hours = h < 10 ? "0" + h : h.toString();
var minutes = min < 10 ? "0" + min : min.toString();
return year + month + day + "T" + hours + minutes + "00Z";
};
var getDate = function (str, end) {
var date = new Date(str);
if (end) {
date.setDate(date.getDate() + 1);
}
var m = date.getUTCMonth() + 1;
var d = date.getUTCDate();
var year = date.getUTCFullYear().toString();
var month = m < 10 ? "0" + m : m.toString();
var day = d < 10 ? "0" + d : d.toString();
return year+month+day;
};
var MINUTE = 60;
var HOUR = MINUTE * 60;
var DAY = HOUR * 24;
module.main = function (userDoc) {
var content = userDoc.content;
var ICS = [
'BEGIN:VCALENDAR',
'VERSION:2.0',
'PRODID:-//CryptPad//CryptPad Calendar '+Pages.versionString+'//EN',
'METHOD:PUBLISH',
];
Object.keys(content).forEach(function (uid) {
var data = content[uid];
// DTSTAMP: now...
// UID: uid
var start, end;
if (data.isAllDay && data.startDay && data.endDay) {
start = "DTSTART;VALUE=DATE:" + getDate(data.startDay);
end = "DTEND;VALUE=DATE:" + getDate(data.endDay, true);
} else {
start = "DTSTART:"+getICSDate(data.start);
end = "DTEND:"+getICSDate(data.end);
}
Array.prototype.push.apply(ICS, [
'BEGIN:VEVENT',
'DTSTAMP:'+getICSDate(+new Date()),
'UID:'+uid,
start,
end,
'SUMMARY:'+ data.title,
'LOCATION:'+ data.location,
]);
if (Array.isArray(data.reminders)) {
data.reminders.forEach(function (valueMin) {
var time = valueMin * 60;
var days = Math.floor(time / DAY);
time -= days * DAY;
var hours = Math.floor(time / HOUR);
time -= hours * HOUR;
var minutes = Math.floor(time / MINUTE);
time -= minutes * MINUTE;
var seconds = time;
var str = "-P" + days + "D";
if (hours || minutes || seconds) {
str += "T" + hours + "H" + minutes + "M" + seconds + "S";
}
Array.prototype.push.apply(ICS, [
'BEGIN:VALARM',
'ACTION:DISPLAY',
'DESCRIPTION:This is an event reminder',
'TRIGGER:'+str,
'END:VALARM'
]);
});
}
if (Array.isArray(data.cp_hidden)) {
Array.prototype.push.apply(ICS, data.cp_hidden);
}
ICS.push('END:VEVENT');
});
ICS.push('END:VCALENDAR');
return new Blob([ ICS.join('\n') ], { type: 'text/calendar;charset=utf-8' });
};
module.import = function (content, id, cb) {
require(['/lib/ical.min.js'], function () {
var ICAL = window.ICAL;
var res = {};
var vcalendar;
try {
var jcalData = ICAL.parse(content);
vcalendar = new ICAL.Component(jcalData);
} catch (e) {
return void cb(e);
}
//var method = vcalendar.getFirstPropertyValue('method');
//if (method !== "PUBLISH") { return void cb('NOT_SUPPORTED'); }
// Add all timezones in iCalendar object to TimezoneService
// if they are not already registered.
var timezones = vcalendar.getAllSubcomponents("vtimezone");
timezones.forEach(function (timezone) {
if (!(ICAL.TimezoneService.has(timezone.getFirstPropertyValue("tzid")))) {
ICAL.TimezoneService.register(timezone);
}
});
var events = vcalendar.getAllSubcomponents('vevent');
events.forEach(function (ev) {
var uid = ev.getFirstPropertyValue('uid');
if (!uid) { return; }
// Get start and end time
var isAllDay = false;
var start = ev.getFirstPropertyValue('dtstart');
var end = ev.getFirstPropertyValue('dtend');
if (start.isDate && end.isDate) {
isAllDay = true;
start = String(start);
end.adjust(-1); // Substract one day
end = String(end);
} else {
start = +start.toJSDate();
end = +end.toJSDate();
}
// Store other properties
var used = ['dtstart', 'dtend', 'uid', 'summary', 'location', 'dtstamp'];
var hidden = [];
ev.getAllProperties().forEach(function (p) {
if (used.indexOf(p.name) !== -1) { return; }
// This is an unused property
hidden.push(p.toICALString());
});
// Get reminders
var reminders = [];
ev.getAllSubcomponents('valarm').forEach(function (al) {
var action = al.getFirstPropertyValue('action');
if (action !== 'DISPLAY') {
// Email notification: keep it in "hidden" and create a cryptpad notification
hidden.push(al.toString());
}
var trigger = al.getFirstPropertyValue('trigger');
var minutes = -trigger.toSeconds() / 60;
if (reminders.indexOf(minutes) === -1) { reminders.push(minutes); }
});
// Create event
res[uid] = {
calendarId: id,
id: uid,
category: 'time',
title: ev.getFirstPropertyValue('summary'),
location: ev.getFirstPropertyValue('location'),
isAllDay: isAllDay,
start: start,
end: end,
reminders: reminders,
cp_hidden: hidden
};
if (!hidden.length) { delete res[uid].cp_hidden; }
if (!reminders.length) { delete res[uid].reminders; }
});
cb(null, res);
});
};
return module;
});

@ -1,5 +1,6 @@
define([
'jquery',
'json.sortify',
'/bower_components/chainpad-crypto/crypto.js',
'/common/toolbar.js',
'/bower_components/nthen/index.js',
@ -15,17 +16,20 @@ define([
'/customize/messages.js',
'/customize/application_config.js',
'/lib/calendar/tui-calendar.min.js',
'/calendar/export.js',
'/common/inner/share.js',
'/common/inner/access.js',
'/common/inner/properties.js',
'/common/jscolor.js',
'/bower_components/file-saver/FileSaver.min.js',
'css!/lib/calendar/tui-calendar.min.css',
'css!/bower_components/components-font-awesome/css/font-awesome.min.css',
'less!/calendar/app-calendar.less',
], function (
$,
JSONSortify,
Crypto,
Toolbar,
nThen,
@ -41,9 +45,11 @@ define([
Messages,
AppConfig,
Calendar,
Export,
Share, Access, Properties
)
{
var SaveAs = window.saveAs;
var APP = window.APP = {
calendars: {}
};
@ -52,31 +58,6 @@ define([
var metadataMgr;
var sframeChan;
Messages.calendar = "BETA Calendar"; // XXX
Messages.calendar_default = "My calendar"; // XXX
Messages.calendar_new = "New calendar"; // XXX
Messages.calendar_day = "Day";
Messages.calendar_week = "Week";
Messages.calendar_month = "Month";
Messages.calendar_today = "Today";
Messages.calendar_more = "{0} more";
Messages.calendar_deleteConfirm = "Are you sure you want to delete this calendar from your account?";
Messages.calendar_deleteTeamConfirm = "Are you sure you want to delete this calendar from this team?";
Messages.calendar_deleteOwned = " It will still be visible for the users it has been shared with.";
Messages.calendar_errorNoCalendar = "No editable calendar selected!";
Messages.calendar_myCalendars = "My calendars";
Messages.calendar_tempCalendar = "Temp calendar";
Messages.calendar_import = "Import to my calendars";
Messages.calendar_newEvent = "New event";
Messages.calendar_new = "New calendar";
Messages.calendar_dateRange = "{0} - {1}";
Messages.calendar_dateTimeRange = "{0} {1} - {2}";
Messages.calendar_update = "Update";
Messages.calendar_title = "Title";
Messages.calendar_loc = "Location";
Messages.calendar_location = "Location: {0}";
Messages.calendar_allDay = "All day";
var onCalendarsUpdate = Util.mkEvent();
var newCalendar = function (data, cb) {
@ -103,6 +84,12 @@ Messages.calendar_allDay = "All day";
cb(null, obj);
});
};
var importICSCalendar = function (data, cb) {
APP.module.execCommand('IMPORT_ICS', data, function (obj) {
if (obj && obj.error) { return void cb(obj.error); }
cb(null, obj);
});
};
var newEvent = function (data, cb) {
APP.module.execCommand('CREATE_EVENT', data, function (obj) {
if (obj && obj.error) { return void cb(obj.error); }
@ -128,16 +115,19 @@ Messages.calendar_allDay = "All day";
var brightness = Math.round(((parseInt(rgb[0]) * 299) +
(parseInt(rgb[1]) * 587) +
(parseInt(rgb[2]) * 114)) / 1000);
return (brightness > 125) ? 'black' : 'white';
return (brightness > 125) ? '#424242' : '#EEEEEE';
};
var getWeekDays = function () {
var getWeekDays = function (large) {
var baseDate = new Date(Date.UTC(2017, 0, 1)); // just a Sunday
var weekDays = [];
for(var i = 0; i < 7; i++) {
weekDays.push(baseDate.toLocaleDateString(undefined, { weekday: 'long' }));
baseDate.setDate(baseDate.getDate() + 1);
}
if (!large) {
weekDays = weekDays.map(function (day) { return day.slice(0,3); });
}
return weekDays.map(function (day) { return day.replace(/^./, function (str) { return str.toUpperCase(); }); });
};
@ -161,7 +151,17 @@ Messages.calendar_allDay = "All day";
};
var getSchedules = function () {
var s = [];
Object.keys(APP.calendars).forEach(function (id) {
var calendars = Object.keys(APP.calendars);
if (APP.currentCalendar) {
var currentCal = calendars.filter(function (id) {
var c = APP.calendars[id];
var t = c.teams || [];
if (id !== APP.currentCalendar) { return; }
return t.length === 1 && t[0] === 0;
});
if (currentCal.length) { calendars = currentCal; }
}
calendars.forEach(function (id) {
var c = APP.calendars[id];
if (c.hidden || c.restricted || c.loading) { return; }
var data = c.content || {};
@ -230,11 +230,17 @@ Messages.calendar_allDay = "All day";
})()) { getTime = undefined; }
var templates = {
popupSave: function (obj) {
APP.editModalData = obj.data && obj.data.root;
return Messages.settings_save;
},
popupUpdate: function(obj) {
APP.editModalData = obj.data && obj.data.root;
return Messages.calendar_update;
},
monthGridHeaderExceed: function(hiddenSchedules) {
return '<span class="tui-full-calendar-weekday-grid-more-schedules">' + Messages._getKey('calendar_more', [hiddenSchedules]) + '</span>';
},
popupSave: function () { return Messages.settings_save; },
popupUpdate: function() { return Messages.calendar_update; },
popupEdit: function() { return Messages.poll_edit; },
popupDelete: function() { return Messages.kanban_delete; },
popupDetailLocation: function(schedule) {
@ -276,7 +282,6 @@ Messages.calendar_allDay = "All day";
}
};
// XXX Note: always create calendars in your own proxy. If you want a team calendar, you can share it with the team later.
var editCalendar = function (id) {
var isNew = !id;
var data = APP.calendars[id];
@ -370,7 +375,7 @@ Messages.calendar_allDay = "All day";
}
});
}
if (data.teams.indexOf(1) === -1 || teamId === 0) {
if (APP.loggedIn && (data.teams.indexOf(1) === -1 || teamId === 0)) {
options.push({
tag: 'a',
attributes: {
@ -382,10 +387,10 @@ Messages.calendar_allDay = "All day";
importCalendar({
id: id,
teamId: teamId
}, function (obj) {
if (obj && obj.error) {
console.error(obj.error);
return void UI.warn(obj.error);
}, function (err) {
if (err) {
console.error(err);
return void UI.warn(Messages.error);
}
});
return true;
@ -411,7 +416,7 @@ Messages.calendar_allDay = "All day";
pathname: "/calendar/",
friends: friends,
title: title,
password: cal.password, // XXX support passwords
password: cal.password,
calendar: {
title: title,
color: color,
@ -438,7 +443,7 @@ Messages.calendar_allDay = "All day";
var href = Hash.hashToHref(h.editHash || h.viewHash, 'calendar');
Access.getAccessModal(common, {
title: title,
password: cal.password, // XXX support passwords
password: cal.password,
calendar: {
title: title,
color: color,
@ -453,6 +458,79 @@ Messages.calendar_allDay = "All day";
return true;
}
});
if (!data.readOnly) {
options.push({
tag: 'a',
attributes: {
'class': 'fa fa-upload',
},
content: h('span', Messages.importButton),
action: function () {
UIElements.importContent('text/calendar', function (res) {
Export.import(res, id, function (err, json) {
if (err) { return void UI.warn(Messages.importError); }
importICSCalendar({
id: id,
json: json
}, function (err) {
if (err) { return void UI.warn(Messages.error); }
UI.log(Messages.saved);
});
});
}, {
accept: ['.ics']
})();
return true;
}
});
}
options.push({
tag: 'a',
attributes: {
'class': 'fa fa-download',
},
content: h('span', Messages.exportButton),
action: function (e) {
e.stopPropagation();
var cal = APP.calendars[id];
var suggestion = Util.find(cal, ['content', 'metadata', 'title']);
var types = [];
types.push({
tag: 'a',
attributes: {
'data-value': '.ics',
'href': '#'
},
content: '.ics'
});
var dropdownConfig = {
text: '.ics', // Button initial text
caretDown: true,
options: types, // Entries displayed in the menu
isSelect: true,
initialValue: '.ics',
common: common
};
var $select = UIElements.createDropdown(dropdownConfig);
UI.prompt(Messages.exportPrompt,
Util.fixFileName(suggestion), function (filename)
{
if (!(typeof(filename) === 'string' && filename)) { return; }
var ext = $select.getValue();
filename = filename + ext;
var blob = Export.main(cal.content);
SaveAs(blob, filename);
}, {
typeInput: $select[0]
});
return true;
}
});
options.push({
tag: 'a',
attributes: {
@ -490,15 +568,15 @@ Messages.calendar_allDay = "All day";
action: function (e) {
e.stopPropagation();
var cal = APP.calendars[id];
var key = Messages.calendar_deleteConfirm;
var teams = (cal && cal.teams) || [];
var text = [ Messages.calendar_deleteConfirm ];
if (teams.length === 1 && teams[0] !== 1) {
key = Messages.calendar_deleteTeamConfirm;
text[0] = Messages.calendar_deleteTeamConfirm;
}
if (cal.owned) {
key += Messages.calendar_deleteOwned;
text = text.concat([' ', Messages.calendar_deleteOwned]);
}
UI.confirm(Messages.calendar_deleteConfirm, function (yes) {
UI.confirm(h('span', text), function (yes) {
if (!yes) { return; }
deleteCalendar({
id: id,
@ -522,7 +600,6 @@ Messages.calendar_allDay = "All day";
return UIElements.createDropdown(dropdownConfig)[0];
};
var makeCalendarEntry = function (id, teamId) {
// XXX handle RESTRICTED calendars (data.restricted)
var data = APP.calendars[id];
var edit;
if (data.loading) {
@ -534,18 +611,25 @@ Messages.calendar_allDay = "All day";
if (!md) { return; }
var active = data.hidden ? '' : '.cp-active';
var restricted = data.restricted ? '.cp-restricted' : '';
var calendar = h('div.cp-calendar-entry'+active+restricted, {
var temp = teamId === 0 ? '.cp-unclickable' : '';
var calendar = h('div.cp-calendar-entry'+active+restricted+temp, {
'data-uid': id
}, [
h('span.cp-calendar-color', {
h('span.cp-calendar-icon', {
style: 'background-color: '+md.color+';'
}, [
h('i.cp-calendar-active.fa.fa-calendar', {
style: 'color: '+getContrast(md.color)+';'
}),
h('i.cp-calendar-inactive.fa.fa-calendar-o')
]),
h('span.cp-calendar-title', md.title),
data.restricted ? h('i.fa.fa-ban', {title: Messages.fm_restricted}) :
(isReadOnly(id, teamId) ? h('i.fa.fa-eye', {title: Messages.readonly}) : undefined),
edit
]);
$(calendar).click(function () {
var $calendar = $(calendar).click(function () {
if (teamId === 0) { return; }
data.hidden = !data.hidden;
if (APP.$calendars) {
APP.$calendars.find('[data-uid="'+id+'"]').toggleClass('cp-active', !data.hidden);
@ -555,6 +639,12 @@ Messages.calendar_allDay = "All day";
renderCalendar();
});
if (!data.loading) {
$calendar.contextmenu(function (ev) {
ev.preventDefault();
$(edit).click();
});
}
if (APP.$calendars) { APP.$calendars.append(calendar); }
return calendar;
};
@ -568,26 +658,63 @@ Messages.calendar_allDay = "All day";
var filter = function (teamId) {
return Object.keys(APP.calendars || {}).filter(function (id) {
var cal = APP.calendars[id] || {};
var teams = cal.teams || [];
return teams.indexOf(typeof(teamId) !== "undefined" ? teamId : 1) !== -1;
var teams = (cal.teams || []).map(function (tId) { return Number(tId); });
return teams.indexOf(typeof(teamId) !== "undefined" ? Number(teamId) : 1) !== -1;
});
};
var tempCalendars = filter(0);
if (tempCalendars.length) {
if (tempCalendars.length && tempCalendars[0] === APP.currentCalendar) {
APP.$calendars.append(h('div.cp-calendar-team', [
h('span', Messages.calendar_tempCalendar)
]));
makeCalendarEntry(tempCalendars[0], 0);
var importTemp = h('button', [
h('i.fa.fa-calendar-plus-o'),
h('span', Messages.calendar_import_temp),
h('span')
]);
$(importTemp).click(function () {
importCalendar({
id: tempCalendars[0],
teamId: 0
}, function (err) {
if (err) {
console.error(err);
return void UI.warn(Messages.error);
}
});
});
if (APP.loggedIn) {
APP.$calendars.append(h('div.cp-calendar-entry.cp-ghost', importTemp));
}
return;
}
var myCalendars = filter(1);
if (myCalendars.length) {
var user = metadataMgr.getUserData();
var avatar = h('span.cp-avatar');
var name = user.name || Messages.anonymous;
common.displayAvatar($(avatar), user.avatar, name);
APP.$calendars.append(h('div.cp-calendar-team', [
h('span', Messages.calendar_myCalendars)
avatar,
h('span.cp-name', {title: name}, name)
]));
}
myCalendars.forEach(function (id) {
makeCalendarEntry(id, 1);
});
// Add new button
var $newContainer = $(h('div.cp-calendar-entry.cp-ghost')).appendTo($calendars);
var newButton = h('button', [
h('i.fa.fa-calendar-plus-o'),
h('span', Messages.calendar_new),
h('span')
]);
$(newButton).click(function () {
editCalendar();
}).appendTo($newContainer);
Object.keys(privateData.teams).forEach(function (teamId) {
var calendars = filter(teamId);
if (!calendars.length) { return; }
@ -602,26 +729,30 @@ Messages.calendar_allDay = "All day";
makeCalendarEntry(id, teamId);
});
});
// Add new button
var $newContainer = $(h('div.cp-calendar-entry.cp-ghost')).appendTo($calendars);
var newButton = h('button', [
h('i.fa.fa-plus'),
h('span', Messages.calendar_new),
h('span')
]);
$(newButton).click(function () {
editCalendar();
}).appendTo($newContainer);
});
onCalendarsUpdate.fire();
};
var ISO8601_week_no = function (dt) {
var tdt = new Date(dt.valueOf());
var dayn = (dt.getDay() + 6) % 7;
tdt.setDate(tdt.getDate() - dayn + 3);
var firstThursday = tdt.valueOf();
tdt.setMonth(0, 1);
if (tdt.getDay() !== 4) {
tdt.setMonth(0, 1 + ((4 - tdt.getDay()) + 7) % 7);
}
return 1 + Math.ceil((firstThursday - tdt) / 604800000);
};
var updateDateRange = function () {
var range = APP.calendar._renderRange;
var start = range.start._date.toLocaleDateString();
var end = range.end._date.toLocaleDateString();
var week = ISO8601_week_no(range.start._date);
var date = [
h('b.cp-small', Messages._getKey('calendar_weekNumber', [week])),
h('b', start),
h('span', ' - '),
h('b', end),
@ -654,6 +785,7 @@ Messages.calendar_allDay = "All day";
h('div#cp-sidebarlayout-rightside')
]);
var large = $(window).width() >= 800;
var cal = APP.calendar = new Calendar('#cp-sidebarlayout-rightside', {
defaultView: view || 'week', // weekly view option
taskView: false,
@ -663,24 +795,42 @@ Messages.calendar_allDay = "All day";
calendars: getCalendars(),
template: templates,
month: {
daynames: getWeekDays(),
daynames: getWeekDays(large),
startDayOfWeek: 1,
},
week: {
daynames: getWeekDays(large),
startDayOfWeek: 1,
}
});
$(window).on('resize', function () {
var _large = $(window).width() >= 800;
if (large !== _large) {
large = _large;
cal.setOptions({
month: {
daynames: getWeekDays(_large),
startDayOfWeek: 1,
},
week: {
daynames: getWeekDays(),
daynames: getWeekDays(_large),
startDayOfWeek: 1,
}
});
}
});
makeLeftside(cal, $(leftside));
cal.on('beforeCreateSchedule', function(event) {
// XXX Recurrence (later)
// TODO Recurrence (later)
// On creation, select a recurrence rule (daily / weekly / monthly / more weird rules)
// then mark it under recurrence rule with a uid (the same for all the recurring events)
// ie: recurrenceRule: DAILY|{uid}
// Use template to hide "recurrenceRule" from the detailPopup or at least to use
// a non technical value
var reminders = APP.notificationsEntries;
var startDate = event.start._date;
var endDate = event.end._date;
@ -694,6 +844,7 @@ Messages.calendar_allDay = "All day";
start: +startDate,
isAllDay: event.isAllDay,
end: +endDate,
reminders: reminders,
};
newEvent(schedule, function (err) {
@ -711,6 +862,12 @@ Messages.calendar_allDay = "All day";
if (changes.start) { changes.start = +new Date(changes.start._date); }
var old = event.schedule;
var oldReminders = Util.find(APP.calendars, [old.calendarId, 'content', 'content', old.id, 'reminders']);
var reminders = APP.notificationsEntries;
if (JSONSortify(oldReminders || []) !== JSONSortify(reminders)) {
changes.reminders = reminders;
}
updateEvent({
ev: old,
changes: changes
@ -780,7 +937,7 @@ Messages.calendar_allDay = "All day";
APP.toolbar.$bottomR.append($block);
// New event button
var newEventBtn = h('button', [
var newEventBtn = h('button.cp-calendar-newevent', [
h('i.fa.fa-plus'),
h('span', Messages.calendar_newEvent)
]);
@ -811,6 +968,116 @@ Messages.calendar_allDay = "All day";
};
var parseNotif = function (minutes) {
var res = {
unit: 'minutes',
value: minutes
};
var hours = minutes / 60;
if (!Number.isInteger(hours)) { return res; }
res.unit = 'hours';
res.value = hours;
var days = hours / 24;
if (!Number.isInteger(days)) { return res; }
res.unit = 'days';
res.value = days;
return res;
};
var getNotificationDropdown = function () {
var ev = APP.editModalData;
var calId = ev.selectedCal.id;
// DEFAULT HERE [10] ==> 10 minutes before the event
var oldReminders = Util.find(APP.calendars, [calId, 'content', 'content', ev.id, 'reminders']) || [10];
APP.notificationsEntries = [];
var number = h('input.tui-full-calendar-content', {
type: "number",
value: 10,
min: 1,
max: 60
});
var $number = $(number);
var options = ['minutes', 'hours', 'days'].map(function (k) {
return {
tag: 'a',
attributes: {
'class': 'cp-calendar-reminder',
'data-value': k,
'href': '#',
},
content: Messages['calendar_'+k]
// Messages.calendar_minutes
// Messages.calendar_hours
// Messages.calendar_days
};
});
var dropdownConfig = {
text: Messages.calendar_minutes,
options: options, // Entries displayed in the menu
isSelect: true,
common: common,
buttonCls: 'btn btn-secondary',
caretDown: true,
};
var $block = UIElements.createDropdown(dropdownConfig);
$block.setValue('minutes');
var $types = $block.find('a');
$types.click(function () {
var mode = $(this).attr('data-value');
var max = mode === "minutes" ? 60 : 24;
$number.attr('max', max);
if ($number.val() > max) { $number.val(max); }
});
var addNotif = h('button.btn.btn-primary-outline.fa.fa-plus');
var $list = $(h('div.cp-calendar-notif-list'));
var listContainer = h('div.cp-calendar-notif-list-container', [
h('span.cp-notif-label', Messages.calendar_notifications),
$list[0],
h('span.cp-notif-empty', Messages.calendar_noNotification)
]);
var addNotification = function (unit, value) {
var unitValue = (unit === "minutes") ? 1 : (unit === "hours" ? 60 : (60*24));
var del = h('button.btn.btn-danger-outline.small.fa.fa-times');
var minutes = value * unitValue;
if ($list.find('[data-minutes="'+minutes+'"]').length) { return; }
var span = h('span.cp-notif-entry', {
'data-minutes': minutes
}, [
h('span.cp-notif-value', [
h('span', value),
h('span', Messages['calendar_'+unit]),
h('span.cp-before', Messages.calendar_before)
]),
del
]);
$(del).click(function () {
$(span).remove();
var idx = APP.notificationsEntries.indexOf(minutes);
APP.notificationsEntries.splice(idx, 1);
});
$list.append(span);
APP.notificationsEntries.push(minutes);
};
$(addNotif).click(function () {
var unit = $block.getValue();
var value = $number.val();
addNotification(unit, value);
});
oldReminders.forEach(function (minutes) {
var p = parseNotif(minutes);
addNotification(p.unit, p.value);
});
return h('div.tui-full-calendar-popup-section.cp-calendar-add-notif', [
listContainer,
h('div.cp-calendar-notif-form', [
h('span.cp-notif-label', Messages.calendar_addNotification),
number,
$block[0],
addNotif
])
]);
};
var createToolbar = function () {
var displayed = ['useradmin', 'newpad', 'limit', 'pageTitle', 'notifications'];
var configTb = {
@ -846,6 +1113,8 @@ Messages.calendar_allDay = "All day";
var privateData = metadataMgr.getPrivateData();
var user = metadataMgr.getUserData();
APP.loggedIn = common.isLoggedIn();
common.setTabTitle(Messages.calendar);
// Fix flatpickr selection
@ -900,6 +1169,10 @@ Messages.calendar_allDay = "All day";
var isUpdate = Boolean($el.find('#tui-full-calendar-schedule-title').val());
if (!isUpdate) { $el.find('.tui-full-calendar-dropdown-menu li').first().click(); }
var $button = $el.find('.tui-full-calendar-section-button-save');
var div = getNotificationDropdown();
$button.before(div);
var $cbox = $el.find('#tui-full-calendar-schedule-allday');
var $start = $el.find('.tui-full-calendar-section-start-date');
var $dash = $el.find('.tui-full-calendar-section-date-dash');
@ -979,6 +1252,11 @@ Messages.calendar_allDay = "All day";
var store = window.cryptpadStore;
APP.module.execCommand('SUBSCRIBE', null, function (obj) {
if (obj.empty && !privateData.calendarHash) {
if (!privateData.loggedIn) {
return void UI.errorLoadingScreen(Messages.mustLogin, false, function () {
common.setLoginRedirect('login');
});
}
// No calendar yet, create one
newCalendar({
teamId: 1,
@ -986,15 +1264,18 @@ Messages.calendar_allDay = "All day";
color: user.color,
title: Messages.calendar_default
}, function (err) {
if (err) { return void UI.errorLoadingScreen(Messages.error); } // XXX
if (err) { return void UI.errorLoadingScreen(Messages.error); }
store.get('calendarView', makeCalendar);
UI.removeLoadingScreen();
});
return;
}
if (privateData.calendarHash) {
var hash = privateData.hashes.editHash || privateData.hashes.viewHash;
var secret = Hash.getSecrets('calendar', hash, privateData.password);
APP.currentCalendar = secret.channel;
APP.module.execCommand('OPEN', {
hash: privateData.hashes.editHash || privateData.hashes.viewHash,
hash: hash,
password: privateData.password
}, function (obj) {
if (obj && obj.error) { console.error(obj.error); }

@ -1,7 +1,6 @@
@import (reference) "../include/colortheme-all.less";
@import (reference) "../include/font.less";
//@import (reference) "../include/forms.less";
@import (reference) "../include/alertify.less";
@import (reference) "../../customize/src/less2/include/colortheme-all.less";
@import (reference) "../../customize/src/less2/include/font.less";
@import (reference) "../../customize/src/less2/include/alertify.less";
html, body {
.font_main();
@ -55,9 +54,16 @@ html, body {
word-break: break-word;
padding: 5px;
//font-size: 16px;
border: 1px solid red;
&.cp-danger {
border: 1px solid @cp_alerts-danger-bg;
background-color: @cp_alerts-danger-bg;
color: @cp_alerts-danger-text;
}
&.cp-warning {
border: 1px solid @cp_alerts-warning-bg;
background-color: @cp_alerts-warning-bg;
color: @cp_alerts-warning-text;
}
code {
word-break: keep-all;
font-style: italic;
@ -66,6 +72,9 @@ html, body {
color: @cryptpad_color_link;
}
}
.cp-app-checkup-version {
text-decoration: underline;
}
iframe {
display: none;

@ -12,13 +12,14 @@ define([
'/common/common-util.js',
'/common/pinpad.js',
'/common/outer/network-config.js',
'/customize/pages.js',
'/bower_components/tweetnacl/nacl-fast.min.js',
'css!/bower_components/components-font-awesome/css/font-awesome.min.css',
'less!/customize/src/less2/pages/page-checkup.less',
'less!/checkup/app-checkup.less',
], function ($, ApiConfig, Assertions, h, Messages, DomReady,
nThen, SFCommonO, Login, Hash, Util, Pinpad,
NetConfig) {
NetConfig, Pages) {
var Assert = Assertions();
var trimSlashes = function (s) {
if (typeof(s) !== 'string') { return s; }
@ -26,7 +27,7 @@ define([
};
var assert = function (f, msg) {
Assert(f, msg || h('span.advisory-text'));
Assert(f, msg || h('span.advisory-text.cp-danger'));
};
var CONFIG_PATH = function () {
@ -243,7 +244,7 @@ define([
opt.keys = secret.keys;
opt.channelHex = secret.channel;
var RT, rpc, exists;
var RT, rpc, exists, restricted;
nThen(function (waitFor) {
Util.fetch(blockUrl, waitFor(function (err) {
@ -285,6 +286,12 @@ define([
// Write block
if (exists) { return; }
rpc.writeLoginBlock(blockRequest, waitFor(function (e) {
// we should tolerate restricted registration
// and proceed to clean up after any data we've created
if (e === 'E_RESTRICTED') {
restricted = true;
return void cb(true);
}
if (e) {
waitFor.abort();
console.error("Can't write login block", e);
@ -292,6 +299,7 @@ define([
}
}));
}).nThen(function (waitFor) {
if (restricted) { return; }
// Read block
Util.fetch(blockUrl, waitFor(function (e) {
if (e) {
@ -303,6 +311,7 @@ define([
}).nThen(function (waitFor) {
// Remove block
rpc.removeLoginBlock(removeRequest, waitFor(function (e) {
if (restricted) { return; } // an ENOENT is expected in the case of restricted registration, but we call this anyway to clean up any mess from previous tests.
if (e) {
waitFor.abort();
console.error("Can't remove login block", e);
@ -357,7 +366,7 @@ define([
});
assert(function (cb, msg) {
msg = msg; // XXX
msg = msg;
return void cb(true);
/*
msg.appendChild(h('span', [
@ -407,6 +416,114 @@ define([
});
});
var checkAPIHeaders = function (url, cb) {
$.ajax(url, {
dataType: 'text',
complete: function (xhr) {
var allHeaders = xhr.getAllResponseHeaders();
var headers = {};
var duplicated = allHeaders.split('\n').some(function (header) {
var duplicate;
header.replace(/([^:]+):(.*)/, function (all, type, value) {
type = type.trim();
if (typeof(headers[type]) !== 'undefined') {
duplicate = true;
}
headers[type] = value.trim();
});
return duplicate;
});
var expect = {
'cross-origin-resource-policy': 'cross-origin',
};
var incorrect = Object.keys(expect).some(function (k) {
var response = xhr.getResponseHeader(k);
if (response !== expect[k]) {
return true;
}
});
if (duplicated || incorrect) { console.error(allHeaders); }
cb(!duplicated && !incorrect);
},
});
};
var INCORRECT_HEADER_TEXT = ' was served with duplicated or incorrect headers. Compare your reverse-proxy configuration against the provided example.';
assert(function (cb, msg) {
var url = '/api/config';
msg.innerText = url + INCORRECT_HEADER_TEXT;
checkAPIHeaders(url, cb);
});
assert(function (cb, msg) {
var url = '/api/broadcast';
msg.innerText = url + INCORRECT_HEADER_TEXT;
checkAPIHeaders(url, cb);
});
var setWarningClass = function (msg) {
$(msg).removeClass('cp-danger').addClass('cp-warning');
};
assert(function (cb, msg) {
var email = ApiConfig.adminEmail;
if (typeof(email) === 'string' && email && email !== 'i.did.not.read.my.config@cryptpad.fr') {
return void cb(true);
}
setWarningClass(msg);
msg.appendChild(h('span', [
'This instance does not provide a valid ',
h('code', 'adminEmail'),
' which can make it difficult to contact its adminstrator to report vulnerabilities or abusive content.',
' This can be configured in ', CONFIG_PATH(), '. ',
RESTART_WARNING(),
]));
cb(email);
});
assert(function (cb, msg) {
var support = ApiConfig.supportMailbox;
setWarningClass(msg);
msg.appendChild(h('span', [
"This instance's encrypted support ticket functionality has not been enabled. This can make it difficult for its users to safely report issues that concern sensitive information. ",
"This can be configured via the ",
h('code', 'supportMailbox'),
" attribute in ",
CONFIG_PATH(),
". ",
RESTART_WARNING(),
]));
cb(support && typeof(support) === 'string' && support.length === 44);
});
assert(function (cb, msg) {
var adminKeys = ApiConfig.adminKeys;
if (Array.isArray(adminKeys) && adminKeys.length >= 1 && typeof(adminKeys[0]) === 'string' && adminKeys[0].length === 44) {
return void cb(true);
}
setWarningClass(msg);
msg.appendChild(h('span', [
"This instance has not been configured to support web administration. This can be enabled by adding a registered user's public signing key to the ",
h('code', 'adminKeys'),
' array in ',
CONFIG_PATH(),
'. ',
RESTART_WARNING(),
]));
cb(false);
});
if (false) {
assert(function (cb, msg) {
msg.innerText = 'fake test to simulate failure';
cb(false);
});
}
var row = function (cells) {
return h('tr', cells.map(function (cell) {
return h('td', cell);
@ -425,6 +542,19 @@ define([
var completed = 0;
var $progress = $('#cp-progress');
var versionStatement = function () {
return h('p', [
"This instance is running ",
h('span.cp-app-checkup-version',[
"CryptPad",
' ',
Pages.versionString,
]),
'.',
]);
};
Assert.run(function (state) {
var errors = state.errors;
var failed = errors.length;
@ -434,10 +564,11 @@ define([
var statusClass = failed? 'failure': 'success';
var failedDetails = "Details found below";
var successDetails = "This checkup only tests the most common configuration issues. You may still experience errors.";
var successDetails = "This checkup only tests the most common configuration issues. You may still experience errors or incorrect behaviour.";
var details = h('p', failed? failedDetails: successDetails);
var summary = h('div.summary.' + statusClass, [
versionStatement(),
h('p', Messages._getKey('assert_numberOfTestsPassed', [
state.passed,
state.total
@ -457,6 +588,7 @@ define([
completed++;
Messages.assert_numberOfTestsCompleted = "{0} / {1} tests completed.";
$progress.html('').append(h('div.report.pending.summary', [
versionStatement(),
h('p', [
h('i.fa.fa-spinner.fa-pulse'),
h('span', Messages._getKey('assert_numberOfTestsCompleted', [completed, total]))

@ -129,6 +129,19 @@
}
@media (max-width: @browser_media-medium-screen) {
#cp-app-code-editor {
&.cp-app-code-present {
#cp-app-code-container { display: none !important; }
#cp-app-code-preview {
flex: 1;
max-width: 100%;
border: 0;
#cp-app-code-preview-content {
margin: 10px;
}
}
}
&:not(.cp-app-code-present) {
#cp-app-code-container {
flex: 1;
max-width: 100%;
@ -138,6 +151,8 @@
display: none !important;
}
}
}
}
#cp-app-code-print {
position: relative;
display: none;

@ -20,7 +20,7 @@ define(function() {
* users and these users will be redirected to the login page if they still try to access
* the app
*/
config.registeredOnlyTypes = ['file', 'contacts', 'notifications', 'support', 'calendar'];
config.registeredOnlyTypes = ['file', 'contacts', 'notifications', 'support'];
/* CryptPad is available is multiple languages, but only English and French are maintained
* by the developers. The other languages may be outdated, and any missing string for a langauge
@ -45,6 +45,13 @@ define(function() {
*/
// config.privacy = 'https://xwiki.com/en/company/PrivacyPolicy';
/* We (the project's developers) include the ability to display a 'Roadmap' in static pages footer.
* This is disabled by default.
* We use this to publish the project's development roadmap, but you can use it however you like.
* To do so, set the following value to an absolute URL.
*/
//config.roadmap = 'https://cryptpad.fr/kanban/#/2/kanban/view/PLM0C3tFWvYhd+EPzXrbT+NxB76Z5DtZhAA5W5hG9wo/';
/* Cryptpad apps use a common API to display notifications to users
* by default, notifications are hidden after 5 seconds
* You can change their duration here (measured in milliseconds)

@ -1434,13 +1434,13 @@ define([
*/
UI.createDrawer = function ($button, $content) {
$button.click(function () {
var topPos = $button[0].getBoundingClientRect().bottom;
$content.toggle();
$button.removeClass('cp-toolbar-button-active');
if ($content.is(':visible')) {
$button.addClass('cp-toolbar-button-active');
$content.focus();
var wh = $(window).height();
var topPos = $button[0].getBoundingClientRect().bottom;
$content.css('max-height', Math.floor(wh - topPos - 1)+'px');
}
});

@ -127,7 +127,7 @@ define([
dcAlert = undefined;
};
var importContent = function (type, f, cfg) {
var importContent = UIElements.importContent = function (type, f, cfg) {
return function () {
var $files = $('<input>', {type:"file"});
if (cfg && cfg.accept) {
@ -575,12 +575,18 @@ define([
}
else if (callback) {*/
// Old import button, used in settings
button
.click(common.prepareFeedback(type))
.click(importContent((data && data.binary) ? 'application/octet-stream' : 'text/plain', callback, {
var importer = importContent((data && data.binary) ? 'application/octet-stream' : 'text/plain', callback, {
accept: data ? data.accept : undefined,
binary: data ? data.binary : undefined
}));
});
var handler = data.first? function () {
data.first(importer);
}: importer; //importContent;
button
.click(common.prepareFeedback(type))
.click(handler);
//}
break;
case 'upload':
@ -788,6 +794,28 @@ define([
h('span.cp-toolbar-name.cp-toolbar-drawer-element', Messages.toolbar_savetodrive)
])).click(common.prepareFeedback(type));
break;
case 'storeindrive':
button = $(h('button.cp-toolbar-storeindrive', {
style: 'display:none;'
}, [
h('i.fa.fa-hdd-o'),
h('span.cp-toolbar-name.cp-toolbar-drawer-element', Messages.toolbar_storeInDrive)
])).click(common.prepareFeedback(type)).click(function () {
$(button).hide();
common.getSframeChannel().query("Q_AUTOSTORE_STORE", null, function (err, obj) {
var error = err || (obj && obj.error);
if (error) {
$(button).show();
if (error === 'E_OVER_LIMIT') {
return void UI.warn(Messages.pinLimitReached);
}
return void UI.warn(Messages.autostore_error);
}
$(document).trigger('cpPadStored');
UI.log(Messages.autostore_saved);
});
});
break;
case 'hashtag':
button = $('<button>', {
'class': 'fa fa-hashtag cp-toolbar-icon-hashtag',
@ -1652,6 +1680,18 @@ define([
},
});
}
if (padType !== 'calendar' && accountName) {
options.push({
tag: 'a',
attributes: {
'class': 'fa fa-calendar',
},
content: h('span', Messages.calendar),
action: function () {
Common.openURL('/calendar/');
},
});
}
if (padType !== 'contacts' && accountName) {
options.push({
tag: 'a',
@ -1833,6 +1873,7 @@ define([
Common.setLoginRedirect('login');
},
});
if (!Config.restrictRegistration) {
options.push({
tag: 'a',
attributes: {'class': 'cp-toolbar-menu-register fa fa-user-plus'},
@ -1842,6 +1883,7 @@ define([
},
});
}
}
var $icon = $('<span>', {'class': 'fa fa-user-secret'});
//var $userbig = $('<span>', {'class': 'big'}).append($displayedName.clone());
var $userButton = $('<div>').append($icon);//.append($userbig);
@ -2797,6 +2839,7 @@ define([
// This pad will be deleted automatically, it shouldn't be stored
if (priv.burnAfterReading) { return; }
var typeMsg = priv.pathname.indexOf('/file/') !== -1 ? Messages.autostore_file :
priv.pathname.indexOf('/drive/') !== -1 ? Messages.autostore_sf :
Messages.autostore_pad;
@ -2808,11 +2851,18 @@ define([
var actions = h('div', [hide, store]);
var initialHide = data && data.autoStore && data.autoStore === -1;
if (initialHide) {
$('.cp-toolbar-storeindrive').show();
UIElements.displayCrowdfunding(common);
return;
}
var modal = UI.cornerPopup(text, actions, footer, {hidden: initialHide});
// Once the store pad popup is created, put the crowdfunding one in the queue
UIElements.displayCrowdfunding(common);
autoStoreModal[priv.channel] = modal;
$(modal.popup).find('.cp-corner-footer a').click(function (e) {
@ -2822,6 +2872,7 @@ define([
$(hide).click(function () {
delete autoStoreModal[priv.channel];
$('.cp-toolbar-storeindrive').show();
modal.delete();
});
var waitingForStoringCb = false;

@ -1735,6 +1735,7 @@ define([
var removeData = obj.Block.remove(blockKeys);
postMessage("DELETE_ACCOUNT", {
keys: Block.keysToRPCFormat(blockKeys),
removeData: removeData
}, function (obj) {
if (obj.state) {
@ -1855,9 +1856,16 @@ define([
};
var content = Block.serialize(JSON.stringify(temp), blockKeys);
console.error("OLD AND NEW BLOCK KEYS", oldBlockKeys, blockKeys);
content.registrationProof = Block.proveAncestor(oldBlockKeys);
console.log("writing new login block");
common.writeLoginBlock(content, waitFor(function (obj) {
var data = {
keys: Block.keysToRPCFormat(blockKeys),
content: content,
};
common.writeLoginBlock(data, waitFor(function (obj) {
if (obj && obj.error) {
waitFor.abort();
return void cb(obj);
@ -1875,8 +1883,11 @@ define([
// Remove block hash
if (blockHash) {
console.log('removing old login block');
var removeData = Block.remove(oldBlockKeys);
common.removeLoginBlock(removeData, waitFor(function (obj) {
var data = {
keys: Block.keysToRPCFormat(oldBlockKeys), // { edPrivate, edPublic }
content: Block.remove(oldBlockKeys),
};
common.removeLoginBlock(data, waitFor(function (obj) {
if (obj && obj.error) { return void console.error(obj.error); }
}));
}
@ -2288,7 +2299,8 @@ define([
cache: rdyCfg.cache,
noDrive: rdyCfg.noDrive,
disableCache: localStorage['CRYPTPAD_STORE|disableCache'],
driveEvents: !rdyCfg.noDrive //rdyCfg.driveEvents // Boolean
driveEvents: !rdyCfg.noDrive, //rdyCfg.driveEvents // Boolean
lastVisit: Number(localStorage.lastVisit) || undefined
};
common.userHash = userHash;
@ -2565,6 +2577,12 @@ define([
AppConfig.afterLogin(common, waitFor());
}
}).nThen(function () {
// Last visit is used to warn you about missed events from your calendars
localStorage.lastVisit = +new Date();
setInterval(function () {
// Bump last visit every minute
localStorage.lastVisit = +new Date();
}, 60000);
f(void 0, env);
if (typeof(window.onhashchange) === 'function') { window.onhashchange(); }
});

@ -9,7 +9,7 @@ define([
'/common/media-tag.js',
'/customize/messages.js',
'/common/highlight/highlight.pack.js',
'/bower_components/diff-dom/diffDOM.js',
'/lib/diff-dom/diffDOM.js',
'/bower_components/tweetnacl/nacl-fast.min.js',
'css!/common/highlight/styles/'+ (window.CryptPad_theme === 'dark' ? 'dark.css' : 'github.css')
],function ($, ApiConfig, Marked, Hash, Util, h, MT, MediaTag, Messages) {
@ -40,6 +40,7 @@ define([
Mermaid = _Mermaid;
Mermaid.initialize({
gantt: { axisFormat: '%m-%d', },
flowchart: { htmlLabels: false, },
theme: (window.CryptPad_theme === 'dark') ? 'dark' : 'default',
"themeCSS": mermaidThemeCSS,
});

@ -122,8 +122,8 @@ define([
var $trashEmptyIcon = $('<span>', {"class": "fa fa-trash-o"});
//var $collapseIcon = $('<span>', {"class": "fa fa-minus-square-o cp-app-drive-icon-expcol"});
var $expandIcon = $('<span>', {"class": "fa fa-plus-square-o cp-app-drive-icon-expcol"});
var $listIcon = $('<button>', {"class": "fa fa-list"});
var $gridIcon = $('<button>', {"class": "fa fa-th-large"});
//var $listIcon = $('<button>', {"class": "fa fa-list"});
//var $gridIcon = $('<button>', {"class": "fa fa-th-large"});
var $sortAscIcon = $('<span>', {"class": "fa fa-angle-up sortasc"});
var $sortDescIcon = $('<span>', {"class": "fa fa-angle-down sortdesc"});
var $closeIcon = $('<span>', {"class": "fa fa-times"});
@ -2407,36 +2407,52 @@ define([
return $box;
};
var getOppositeViewMode = function (viewMode) {
viewMode = viewMode || getViewMode();
var newViewMode = viewMode === 'grid'? 'list': 'grid';
return newViewMode;
};
// Create the button allowing the user to switch from list to icons modes
var createViewModeButton = function ($container) {
var $listButton = $listIcon.clone();
var $gridButton = $gridIcon.clone();
$listButton.click(function () {
$gridButton.show();
$listButton.hide();
setViewMode('list');
$('#' + FOLDER_CONTENT_ID).removeClass('cp-app-drive-content-grid');
$('#' + FOLDER_CONTENT_ID).addClass('cp-app-drive-content-list');
Feedback.send('DRIVE_LIST_MODE');
});
$gridButton.click(function () {
$listButton.show();
$gridButton.hide();
setViewMode('grid');
$('#' + FOLDER_CONTENT_ID).addClass('cp-app-drive-content-grid');
$('#' + FOLDER_CONTENT_ID).removeClass('cp-app-drive-content-list');
Feedback.send('DRIVE_GRID_MODE');
});
var viewMode = getViewMode();
var gridIcon = h('i.fa.fa-th-large', { title: Messages.fm_viewGridButton });
var listIcon = h('i.fa.fa-list', { title: Messages.fm_viewListButton });
if (getViewMode() === 'list') {
$listButton.hide();
var $button = $(h('button.cp-app-drive-viewmode-button', [
gridIcon,
listIcon
]));
var $gridIcon = $(gridIcon);
var $listIcon = $(listIcon);
var showMode = function (mode) {
if (mode === 'grid') {
$gridIcon.hide();
$listIcon.show();
} else {
$listIcon.hide();
$gridIcon.show();
}
};
setViewMode(viewMode || 'grid');
showMode(viewMode);
$button.click(function (e) {
console.error(e);
var viewMode = getViewMode();
var newViewMode = getOppositeViewMode(viewMode);
setViewMode(newViewMode);
showMode(newViewMode);
var $folder = $('#' + FOLDER_CONTENT_ID);
if (newViewMode === 'list') {
$folder.removeClass('cp-app-drive-content-grid').addClass('cp-app-drive-content-list');
Feedback.send('DRIVE_LIST_MODE');
} else {
$gridButton.hide();
$folder.addClass('cp-app-drive-content-grid').removeClass('cp-app-drive-content-list');
Feedback.send('DRIVE_GRID_MODE');
}
$listButton.attr('title', Messages.fm_viewListButton);
$gridButton.attr('title', Messages.fm_viewGridButton);
$container.append($listButton).append($gridButton);
});
$container.append($button);
};
var emptyTrashModal = function () {
var ownedInTrash = manager.ownedInTrash();

@ -386,11 +386,11 @@ define([
'tabindex': '-1',
'data-icon': "fa-eye",
}, Messages.pad_mediatagPreview)),
h('li.cp-svg', h('a.cp-app-code-context-openin.dropdown-item', {
h('li', h('a.cp-app-code-context-openin.dropdown-item', {
'tabindex': '-1',
'data-icon': "fa-external-link",
}, Messages.pad_mediatagOpen)),
h('li.cp-svg', h('a.cp-app-code-context-share.dropdown-item', {
h('li', h('a.cp-app-code-context-share.dropdown-item', {
'tabindex': '-1',
'data-icon': "fa-shhare-alt",
}, Messages.pad_mediatagShare)),
@ -398,7 +398,7 @@ define([
'tabindex': '-1',
'data-icon': "fa-cloud-upload",
}, Messages.pad_mediatagImport)),
h('li', h('a.cp-app-code-context-download.dropdown-item', {
h('li.cp-svg', h('a.cp-app-code-context-download.dropdown-item', {
'tabindex': '-1',
'data-icon': "fa-download",
}, Messages.download_mt_button)),
@ -429,6 +429,52 @@ define([
common.importMediaTag($mt);
}
else if ($this.hasClass("cp-app-code-context-download")) {
if ($mt.is('pre.mermaid') || $mt.is('pre.markmap')) {
(function () {
var name = Messages.mediatag_defaultImageName + '.svg';
var svg = $mt.find('svg')[0].cloneNode(true);
$(svg).attr('xmlns', 'http://www.w3.org/2000/svg').attr('width', $mt.width()).attr('height', $mt.height());
$(svg).find('foreignObject').each(function (i, el) {
var $el = $(el);
$el.find('br').after('\n');
$el.find('br').remove();
var t = $el[0].innerText || $el[0].textContent;
t.split('\n').forEach(function (text, i) {
var dy = (i+1)+'em';
$el.after(h('text', {y:0, dy:dy, style: ''}, text));
});
$el.remove();
});
var html = svg.outerHTML;
html = html.replace('<br>', '<br/>');
var b = new Blob([html], { type: 'image/svg+xml' });
window.saveAs(b, name);
})();
return;
}
if ($mt.is('pre.mathjax')) {
(function () {
var name = Messages.mediatag_defaultImageName + '.png';
var svg = $mt.find('> span > svg')[0];
var clone = svg.cloneNode(true);
var html = clone.outerHTML;
var b = new Blob([html], { type: 'image/svg+xml' });
var blobURL = URL.createObjectURL(b);
var i = new Image();
i.onload = function () {
var canvas = document.createElement('canvas');
canvas.width = i.width;
canvas.height = i.height;
var context = canvas.getContext('2d');
context.drawImage(i, 0, 0, i.width, i.height);
canvas.toBlob(function (blob) {
window.saveAs(blob, name);
});
};
i.src = blobURL;
})();
return;
}
var media = Util.find($mt, [0, '_mediaObject']);
if (!media) { return void console.error('no media'); }
if (!media.complete) { return void UI.warn(Messages.mediatag_notReady); }

@ -461,6 +461,69 @@ define([
}
};
handlers['REMINDER'] = function (common, data) {
var content = data.content;
var msg = content.msg.content;
var missed = content.msg.missed;
var start = msg.start;
var title = Util.fixHTML(msg.title);
content.getFormatText = function () {
var now = +new Date();
// Events that have already started
var wasRefresh = content.autorefresh;
content.autorefresh = false;
var nowDateStr = new Date().toLocaleDateString();
var startDate = new Date(start);
if (msg.isAllDay && msg.startDay) {
startDate = new Date(msg.startDay);
}
// Missed events
if (start < now && missed) {
return Messages._getKey('reminder_missed', [title, startDate.toLocaleString()]);
}
// Starting now
if (start < now && wasRefresh) {
return Messages._getKey('reminder_now', [title]);
}
// In progress, is all day
if (start < now && msg.isAllDay) {
return Messages._getKey('reminder_inProgressAllDay', [title]);
}
// In progress, normal event
if (start < now) {
return Messages._getKey('reminder_inProgress', [title, startDate.toLocaleString()]);
}
// Not started yet
// No precise time for allDay events
if (msg.isAllDay) {
return Messages._getKey('reminder_date', [title, startDate.toLocaleDateString()]);
}
// In less than an hour: show countdown in minutes
if ((start - now) < 3600000) {
var minutes = Math.round((start - now) / 60000);
content.autorefresh = true;
return Messages._getKey('reminder_minutes', [title, minutes]);
}
// Not today: show full date
if (nowDateStr !== startDate.toLocaleDateString()) {
return Messages._getKey('reminder_date', [title, startDate.toLocaleString()]);
}
// Today: show time
return Messages._getKey('reminder_time', [title, startDate.toLocaleTimeString()]);
};
if (!content.archived) {
content.dismissHandler = defaultDismiss(common, data);
}
};
// NOTE: don't forget to fixHTML everything returned by "getFormatText"
return {

@ -51,7 +51,6 @@ define([
{
var saveAs = window.saveAs;
var Nacl = window.nacl;
var APP = window.APP = {
$: $,
urlArgs: Util.find(ApiConfig, ['requireConf', 'urlArgs'])
@ -74,7 +73,7 @@ define([
};
var supportsXLSX = function () {
return !(typeof(Atomics) === "undefined" || typeof (SharedArrayBuffer) === "undefined");
return !(typeof(Atomics) === "undefined" || typeof (SharedArrayBuffer) === "undefined" || typeof(WebAssembly) === 'undefined');
};
@ -1066,7 +1065,7 @@ define([
var myId = getId();
content.locks[myId] = content.locks[myId] || {};
var b = obj.block && obj.block[0];
if (type === "sheet") {
if (type === "sheet" || typeof(b) !== "string") {
var uid = Util.uid();
content.locks[myId][uid] = msg;
} else {
@ -1380,21 +1379,7 @@ define([
'#fm-btn-info { display: none !important; }' + // Author name, doc title, etc. in "File" (menu entry)
'#panel-info { display: none !important; }' + // Same but content
'#image-button-from-url { display: none !important; }' + // Inline image settings: replace with url
'#asc-gen257 { display: none !important; }' + // Insert image from url
'#asc-gen1839 { display: none !important; }' + // Image context menu: replace with url
'#asc-gen5883 { display: none !important; }' + // Rightside image menu: replace with url
'#asc-gen1211 { display: none !important; }' + // Slide Image context menu: replace with url
'#asc-gen3880 { display: none !important; }' + // Rightside slide image menu: replace with url
'#asc-gen2218 { display: none !important; }' + // Rightside slide menu: fill slide with image url
'#asc-gen849 { display: none !important; }' + // Toolbar slide: insert image from url
'#asc-gen857 { display: none !important; }' + // Toolbar slide: insert image from url (insert tab)
'#asc-gen180 { display: none !important; }' + // Doc Insert image from url
'#asc-gen1760 { display: none !important; }' + // Doc Image context menu: replace with url
'#asc-gen3319 { display: none !important; }' + // Doc Rightside image menu: replace with url
'.cp-from-url, #textart-button-from-url { display: none !important; }' + // Spellcheck language
'.statusbar .cnt-lang { display: none !important; }' + // Spellcheck language
'.statusbar #btn-doc-spell { display: none !important; }' + // Spellcheck button
'#file-menu-panel .devider { display: none !important; }' + // separator in the "File" menu
@ -1941,7 +1926,7 @@ define([
if (!supportsXLSX()) {
ext = ['.bin'];
warning = '<div class="alert alert-info cp-alert-top">'+Messages.oo_exportChrome+'</div>';
warning = h('div.alert.alert-info.cp-alert-top', Messages.oo_conversionSupport);
}
var types = ext.map(function (val) {
@ -1964,7 +1949,12 @@ define([
};
var $select = UIElements.createDropdown(dropdownConfig);
UI.prompt(Messages.exportPrompt+warning, Util.fixFileName(suggestion), function (filename) {
var promptMessage = h('span', [
Messages.exportPrompt,
warning
]);
UI.prompt(promptMessage, Util.fixFileName(suggestion), function (filename) {
// $select.getValue()
if (!(typeof(filename) === 'string' && filename)) { return; }
var ext = ($select.getValue() || '').slice(1);
@ -2534,20 +2524,36 @@ define([
} else if (type === "doc") {
accept = ['.bin', '.odt', '.docx'];
}
var first;
if (!supportsXLSX()) {
accept = ['.bin'];
first = function (cb) {
var msg = h('span', [
Messages.oo_conversionSupport,
' ', h('span', Messages.oo_importBin),
]);
UI.confirm(msg, function (yes) {
if (yes) {
cb();
}
});
};
}
if (common.isLoggedIn()) {
window.CryptPad_deleteLastCp = deleteLastCp;
var $importXLSX = common.createButton('import', true, {
accept: accept,
binary : ["ods", "xlsx", "odt", "docx", "odp", "pptx"]
binary : ["ods", "xlsx", "odt", "docx", "odp", "pptx"],
first: first,
}, importXLSXFile);
$importXLSX.appendTo(toolbar.$drawer);
common.createButton('hashtag', true).appendTo(toolbar.$drawer);
}
var $store = common.createButton('storeindrive', true);
toolbar.$drawer.append($store);
var $forget = common.createButton('forget', true, {}, function (err) {
if (err) { return; }
setEditable(false);
@ -2682,16 +2688,22 @@ define([
}
// Only execute the following code the first time we call onReady
if (!firstReady) {
setMyId();
oldHashes = JSON.parse(JSON.stringify(content.hashes));
initializing = false;
return void setEditable(!readOnly);
}
firstReady = false;
var useNewDefault = content.version && content.version >= 2;
openRtChannel(function () {
setMyId();
oldHashes = JSON.parse(JSON.stringify(content.hashes));
initializing = false;
// Only execute the following code the first time we call onReady
if (!firstReady) { return void setEditable(!readOnly); }
firstReady = false;
common.openPadChat(APP.onLocal);
if (!readOnly) {
@ -2850,10 +2862,12 @@ define([
common.gotoURL();
});
}
setEditable(true);
//setEditable(true);
try { getEditor().asc_setViewMode(false); } catch (e) {}
offline = false;
} else {
setEditable(false);
try { getEditor().asc_setViewMode(true); } catch (e) {}
//setEditable(false);
offline = true;
UI.findOKButton().click();
UIElements.disconnectAlert();

@ -11578,7 +11578,7 @@ this.getTargetDocContent(undefined,true);if(oTargetDocContent){oState.Pos=oTarge
this.clearTrackObjects();this.resetSelection(undefined,undefined,true);this.changeCurrentState(new AscFormat.NullState(this));return this.loadDocumentStateAfterLoadChanges(oState)},loadDocumentStateAfterLoadChanges:DrawingObjectsController.prototype.loadDocumentStateAfterLoadChanges,checkTrackDrawings:DrawingObjectsController.prototype.checkTrackDrawings,canChangeWrapPolygon:function(){return!this.selection.groupSelection&&!this.selection.textSelection&&!this.selection.chartSelection&&this.selectedObjects.length===
1&&this.selectedObjects[0].canChangeWrapPolygon&&this.selectedObjects[0].canChangeWrapPolygon()&&!this.selectedObjects[0].parent.Is_Inline()},startChangeWrapPolygon:function(){if(this.canChangeWrapPolygon()){var bNeedBehindDoc=this.getCompatibilityMode()<AscCommon.document_compatibility_mode_Word15;if(this.selectedObjects[0].parent.wrappingType!==WRAPPING_TYPE_THROUGH||this.selectedObjects[0].parent.wrappingType!==WRAPPING_TYPE_TIGHT||this.selectedObjects[0].parent.behindDoc!==bNeedBehindDoc)if(false===
this.document.Document_Is_SelectionLocked(changestype_Drawing_Props,{Type:AscCommon.changestype_2_Element_and_Type,Element:this.selectedObjects[0].parent.Get_ParentParagraph(),CheckType:AscCommon.changestype_Paragraph_Content})){this.document.StartAction(AscDFH.historydescription_Document_GrObjectsChangeWrapPolygon);this.selectedObjects[0].parent.Set_WrappingType(WRAPPING_TYPE_TIGHT);this.selectedObjects[0].parent.Set_BehindDoc(bNeedBehindDoc);this.selectedObjects[0].parent.Check_WrapPolygon();this.document.Recalculate();
this.document.UpdateInterface();this.document.FinalizeAction()}this.resetInternalSelection();this.selection.wrapPolygonSelection=this.selectedObjects[0];this.updateOverlay()}},removeById:function(pageIndex,id){var object=g_oTableId.Get_ById(id);if(isRealObject(object)){var hdr_ftr=object.DocumentContent.IsHdrFtr(true);var page=!hdr_ftr?this.graphicPages[pageIndex]:null;if(isRealObject(page))page.delObjectById(id)}},Remove_ById:function(id){for(var i=0;i<this.graphicPages.length;++i)this.removeById(i,
this.document.UpdateInterface();this.document.FinalizeAction()}this.resetInternalSelection();this.selection.wrapPolygonSelection=this.selectedObjects[0];this.updateOverlay()}},removeById:function(pageIndex,id){var object=g_oTableId.Get_ById(id);if(isRealObject(object)){var hdr_ftr=object.DocumentContent&&object.DocumentContent.IsHdrFtr(true);var page=!hdr_ftr?this.graphicPages[pageIndex]:null;if(isRealObject(page))page.delObjectById(id)}},Remove_ById:function(id){for(var i=0;i<this.graphicPages.length;++i)this.removeById(i,
id)},selectById:function(id,pageIndex){this.resetSelection();var obj=g_oTableId.Get_ById(id),nPageIndex=pageIndex;if(obj&&obj.GraphicObj){if(obj.DocumentContent&&obj.DocumentContent.IsHdrFtr()){if(obj.DocumentContent.Get_StartPage_Absolute()!==obj.PageNum)nPageIndex=obj.PageNum}else if(AscFormat.isRealNumber(obj.PageNum))nPageIndex=obj.PageNum;obj.GraphicObj.select(this,nPageIndex)}},calculateAfterChangeTheme:function(){for(var i=0;i<this.drawingObjects.length;++i)this.drawingObjects[i].calculateAfterChangeTheme();
editor.SyncLoadImages(this.urlMap);this.urlMap=[]},updateSelectionState:function(){return},drawSelectionPage:function(pageIndex){var oMatrix=null;if(this.selection.textSelection){if(this.selection.textSelection.selectStartPage===pageIndex){if(this.selection.textSelection.transformText)oMatrix=this.selection.textSelection.transformText.CreateDublicate();this.drawingDocument.UpdateTargetTransform(oMatrix);this.selection.textSelection.getDocContent().DrawSelectionOnPage(0)}}else if(this.selection.groupSelection){if(this.selection.groupSelection.selectStartPage===
pageIndex)this.selection.groupSelection.drawSelectionPage(0)}else if(this.selection.chartSelection&&this.selection.chartSelection.selectStartPage===pageIndex&&this.selection.chartSelection.selection.textSelection){if(this.selection.chartSelection.selection.textSelection.transformText)oMatrix=this.selection.chartSelection.selection.textSelection.transformText.CreateDublicate();this.drawingDocument.UpdateTargetTransform(oMatrix);this.selection.chartSelection.selection.textSelection.getDocContent().DrawSelectionOnPage(0)}},

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

@ -1,4 +1,5 @@
define([
'/api/config',
'json.sortify',
'/common/userObject.js',
'/common/proxy-manager.js',
@ -30,7 +31,7 @@ define([
'/bower_components/netflux-websocket/netflux-client.js',
'/bower_components/nthen/index.js',
'/bower_components/saferphore/index.js',
], function (Sortify, UserObject, ProxyManager, Migrate, Hash, Util, Constants, Feedback,
], function (ApiConfig, Sortify, UserObject, ProxyManager, Migrate, Hash, Util, Constants, Feedback,
Realtime, Messaging, Pinpad, Cache,
SF, Cursor, OnlyOffice, Mailbox, Profile, Team, Messenger, History,
Calendar, NetConfig, AppConfig,
@ -226,8 +227,9 @@ define([
if (store.proxy.mailboxes) {
var mList = Object.keys(store.proxy.mailboxes).map(function (m) {
if (m === "broadcast" && !store.isAdmin) { return; }
return store.proxy.mailboxes[m].channel;
});
}).filter(Boolean);
list = list.concat(mList);
}
@ -449,21 +451,35 @@ define([
};
Store.writeLoginBlock = function (clientId, data, cb) {
store.rpc.writeLoginBlock(data, function (e, res) {
Pinpad.create(store.network, data && data.keys, function (err, rpc) {
if (err) {
return void cb({
error: err,
});
}
rpc.writeLoginBlock(data && data.content, function (e, res) {
cb({
error: e,
data: res
});
});
});
};
Store.removeLoginBlock = function (clientId, data, cb) {
store.rpc.removeLoginBlock(data, function (e, res) {
Pinpad.create(store.network, data && data.keys, function (err, rpc) {
if (err) {
return void cb({
error: err,
});
}
rpc.removeLoginBlock(data && data.content, function (e, res) {
cb({
error: e,
data: res
});
});
});
};
var initRpc = function (clientId, data, cb) {
@ -813,6 +829,7 @@ define([
Store.deleteAccount = function (clientId, data, cb) {
var edPublic = store.proxy.edPublic;
var removeData = data && data.removeData;
var rpcKeys = data && data.keys;
Store.anonRpcMsg(clientId, {
msg: 'GET_METADATA',
data: store.driveChannel
@ -843,8 +860,15 @@ define([
}, waitFor());
}).nThen(function (waitFor) {
if (!removeData) { return; }
var done = waitFor();
Pinpad.create(store.network, rpcKeys, function (err, rpc) {
if (err) {
console.error(err);
return void done();
}
// Delete the block. Don't abort if it fails, it doesn't leak any data.
store.rpc.removeLoginBlock(removeData, waitFor());
rpc.removeLoginBlock(removeData, done);
});
}).nThen(function () {
// Log out current worker
postMessage(clientId, "DELETE_ACCOUNT", token, function () {});
@ -2927,6 +2951,12 @@ define([
onReady(clientId, returned, cb);
});
}
if (rt.proxy.edPublic && Array.isArray(ApiConfig.adminKeys) &&
ApiConfig.adminKeys.indexOf(rt.proxy.edPublic) !== -1) {
store.isAdmin = true;
}
onReady(clientId, returned, cb);
})
.on('change', ['drive', 'migrate'], function () {

@ -12,60 +12,6 @@ define([
], function (Util, Hash, Constants, Realtime, Cache, Messages, nThen, Listmap, Crypto, ChainPad) {
var Calendar = {};
/* TODO
* Calendar
{
href,
roHref,
channel, (pinning)
title, (when created from the UI, own calendar has no title)
color
}
* Own drive
{
calendars: {
uid: calendar,
uid: calendar
}
}
* Team drive
{
calendars: {
uid: calendar,
uid: calendar
}
}
* Calendars are listmap
{
content: {},
metadata: {
title: "pewpewpew"
}
}
ctx.calendars[channel] = {
lm: lm,
proxy: lm.proxy?
stores: [teamId, teamId, 1]
}
* calendar app can subscribe to this module
* when a listmap changes, push an update for this calendar to subscribed tabs
* Ability to open a calendar not stored in the stores but from its URL directly
* No "userlist" visible in the UI
* No framework
*/
var getStore = function (ctx, id) {
if (!id || id === 1) {
return ctx.store;
@ -109,6 +55,15 @@ ctx.calendars[channel] = {
}, ctx.clients);
};
var clearReminders = function (ctx, id) {
var calendar = ctx.calendars[id];
if (!calendar || !calendar.reminders) { return; }
// Clear existing reminders
Object.keys(calendar.reminders).forEach(function (uid) {
if (!Array.isArray(calendar.reminders[uid])) { return; }
calendar.reminders[uid].forEach(function (to) { clearTimeout(to); });
});
};
var closeCalendar = function (ctx, id) {
var ctxCal = ctx.calendars[id];
if (!ctxCal) { return; }
@ -116,6 +71,7 @@ ctx.calendars[channel] = {
// If the calendar doesn't exist in any other team, stop it and delete it from ctx
if (!ctxCal.stores.length) {
ctxCal.lm.stop();
clearReminders(ctx, id);
delete ctx.calendars[id];
}
};
@ -133,6 +89,105 @@ ctx.calendars[channel] = {
if (cal.title !== data.title) { cal.title = data.title; }
});
};
var updateEventReminders = function (ctx, reminders, _ev, useLastVisit) {
var now = +new Date();
var ev = Util.clone(_ev);
var uid = ev.id;
// Clear reminders for this event
if (Array.isArray(reminders[uid])) {
reminders[uid].forEach(function (to) { clearTimeout(to); });
}
reminders[uid] = [];
var last = ctx.store.data.lastVisit;
if (ev.isAllDay) {
if (ev.startDay) { ev.start = +new Date(ev.startDay); }
if (ev.endDay) {
var endDate = new Date(ev.endDay);
endDate.setHours(23);
endDate.setMinutes(59);
endDate.setSeconds(59);
ev.end = +endDate;
}
}
var oneWeekAgo = now - (7 * 24 * 3600 * 1000);
var missed = useLastVisit && ev.start > last && ev.end <= now && ev.end > oneWeekAgo;
if (ev.end <= now && !missed) {
// No reminder for past events
delete reminders[uid];
return;
}
var send = function () {
var hide = Util.find(ctx, ['store', 'proxy', 'settings', 'general', 'calendar', 'hideNotif']);
if (hide) { return; }
var ctime = ev.start <= now ? ev.start : +new Date(); // Correct order for past events
ctx.store.mailbox.showMessage('reminders', {
msg: {
ctime: ctime,
type: "REMINDER",
missed: Boolean(missed),
content: ev
},
hash: 'REMINDER|'+uid
}, null, function () {
});
};
var sendNotif = function () { ctx.Store.onReadyEvt.reg(send); };
var notifs = ev.reminders || [];
notifs.sort(function (a, b) {
return a - b;
});
notifs.some(function (delayMinutes) {
var delay = delayMinutes * 60000;
var time = now + delay;
// setTimeout only work with 32bit timeout values. If the event is too far away,
// ignore this event for now
// FIXME: call this function again in xxx days to reload these missing timeout?
if (ev.start - time >= 2147483647) { return true; }
// If we're too late to send a notification, send it instantly and ignore
// all notifications that were supposed to be sent even earlier
if (ev.start <= time) {
sendNotif();
return true;
}
// It starts in more than "delay": prepare the notification
reminders[uid].push(setTimeout(function () {
sendNotif();
}, (ev.start - time)));
});
};
var addReminders = function (ctx, id, ev) {
var calendar = ctx.calendars[id];
if (!calendar || !calendar.reminders) { return; }
if (calendar.stores.length === 1 && calendar.stores[0] === 0) { return; }
updateEventReminders(ctx, calendar.reminders, ev);
};
var addInitialReminders = function (ctx, id, useLastVisit) {
var calendar = ctx.calendars[id];
if (!calendar || !calendar.reminders) { return; }
if (Object.keys(calendar.reminders).length) { return; } // Already initialized
// No reminders for calendars not stored
if (calendar.stores.length === 1 && calendar.stores[0] === 0) { return; }
// Re-add all reminders
var content = Util.find(calendar, ['proxy', 'content']);
if (!content) { return; }
Object.keys(content).forEach(function (uid) {
updateEventReminders(ctx, calendar.reminders, content[uid], useLastVisit);
});
};
var openChannel = function (ctx, cfg, _cb) {
var cb = Util.once(Util.mkAsync(_cb || function () {}));
var teamId = cfg.storeId;
@ -156,6 +211,10 @@ ctx.calendars[channel] = {
c.lm.setReadOnly(false, upgradeCrypto);
c.readOnly = false;
} else if (teamId === 0) {
// If we open a second tab with the same temp URL, push to tempId
if (c.stores.length === 1 && c.stores[0] === 0 && c.tempId.length && cfg.cId) {
c.tempId.push(cfg.cId);
}
// Existing calendars can't be "temp calendars" (unless they are an upgrade)
return void cb();
}
@ -174,7 +233,10 @@ ctx.calendars[channel] = {
if (c.stores && c.stores.indexOf(teamId) !== -1) { return void cb(); }
// If we store a temp calendar to our account or team, remove this "temp calendar"
if (c.stores.indexOf(0) !== -1) { c.stores.splice(c.stores.indexOf(0), 1); }
if (c.stores.indexOf(0) !== -1) {
c.stores.splice(c.stores.indexOf(0), 1);
c.tempId = [];
}
c.stores.push(teamId);
if (!data.href) {
@ -190,11 +252,17 @@ ctx.calendars[channel] = {
ready: false,
channel: channel,
readOnly: !data.href,
tempId: [],
stores: [teamId],
roStores: data.href ? [] : [teamId],
reminders: {},
hashes: {}
};
if (teamId === 0) {
c.tempId.push(cfg.cId);
}
var parsed = Hash.parsePadUrl(data.href || data.roHref);
var secret = Hash.getSecrets('calendar', parsed.hash, data.password);
@ -215,7 +283,6 @@ ctx.calendars[channel] = {
var onDeleted = function () {
// Remove this calendar from all our teams
// XXX Maybe not? don't remove automatically so that we can tell the user to do so.
c.stores.forEach(function (storeId) {
var store = getStore(ctx, storeId);
if (!store || !store.rpc || !store.proxy.calendars) { return; }
@ -231,6 +298,7 @@ ctx.calendars[channel] = {
if (c.lm) { c.lm.stop(); }
c.stores = [];
sendUpdate(ctx, c);
clearReminders(ctx, channel);
delete ctx.calendars[channel];
};
@ -289,6 +357,7 @@ ctx.calendars[channel] = {
c.cacheready = true;
setTimeout(update);
if (cb) { cb(null, lm.proxy); }
addInitialReminders(ctx, channel, cfg.lastVisitNotif);
}).on('ready', function (info) {
var md = info.metadata;
c.owners = md.owners || [];
@ -305,9 +374,25 @@ ctx.calendars[channel] = {
}
setTimeout(update);
if (cb) { cb(null, lm.proxy); }
addInitialReminders(ctx, channel, cfg.lastVisitNotif);
}).on('change', [], function () {
if (!c.ready) { return; }
setTimeout(update);
}).on('change', ['content'], function (o, n, p) {
if (p.length === 2 && n && !o) { // New event
addReminders(ctx, channel, n);
}
if (p.length === 2 && !n && o) { // Deleted event
addReminders(ctx, channel, {
id: p[1],
start: 0
});
}
if (p.length === 3 && n && o && p[2] === 'start') { // Update event start
setTimeout(function () {
addReminders(ctx, channel, proxy.content[p[1]]);
});
}
}).on('change', ['metadata'], function () {
// if title or color have changed, update our local values
var md = proxy.metadata;
@ -326,6 +411,7 @@ ctx.calendars[channel] = {
}
if (info.error === "ERESTRICTED" ) {
c.restricted = true;
setTimeout(update);
}
cb(info);
});
@ -402,6 +488,7 @@ ctx.calendars[channel] = {
decryptTeamCalendarHref(store, cal);
openChannel(ctx, {
storeId: storeId,
lastVisitNotif: true,
data: cal
});
});
@ -434,11 +521,30 @@ ctx.calendars[channel] = {
});
};
var importICSCalendar = function (ctx, data, cId, cb) {
var id = data.id;
var c = ctx.calendars[id];
if (!c || !c.proxy) { return void cb({error: "ENOENT"}); }
var json = data.json;
c.proxy.content = c.proxy.content || {};
Object.keys(json).forEach(function (uid) {
c.proxy.content[uid] = json[uid];
addReminders(ctx, id, json[uid]);
});
Realtime.whenRealtimeSyncs(c.lm.realtime, function () {
sendUpdate(ctx, c);
cb();
});
};
var openCalendar = function (ctx, data, cId, cb) {
var secret = Hash.getSecrets('calendar', data.hash, data.password);
var hash = Hash.getEditHashFromKeys(secret);
var roHash = Hash.getViewHashFromKeys(secret);
if (!ctx.loggedIn) { hash = undefined; }
var cal = {
href: hash && Hash.hashToHref(hash, 'calendar'),
roHref: roHash && Hash.hashToHref(roHash, 'calendar'),
@ -447,6 +553,7 @@ ctx.calendars[channel] = {
title: '...'
};
openChannel(ctx, {
cId: cId,
storeId: 0,
data: cal
}, cb);
@ -638,6 +745,7 @@ ctx.calendars[channel] = {
c.proxy.content[data.id] = data;
Realtime.whenRealtimeSyncs(c.lm.realtime, function () {
addReminders(ctx, id, data);
sendUpdate(ctx, c);
cb();
});
@ -686,6 +794,18 @@ ctx.calendars[channel] = {
Realtime.whenRealtimeSyncs(c.lm.realtime, waitFor());
if (newC) { Realtime.whenRealtimeSyncs(newC.lm.realtime, waitFor()); }
}).nThen(function () {
if (newC) {
// Move reminders to the new calendar
addReminders(ctx, id, {
id: ev.id,
start: 0
});
addReminders(ctx, ev.calendarId, ev);
} else if (changes.start || changes.reminders || changes.isAllDay) {
// Update reminders
addReminders(ctx, id, ev);
}
sendUpdate(ctx, c);
if (newC) { sendUpdate(ctx, newC); }
cb();
@ -698,6 +818,10 @@ ctx.calendars[channel] = {
c.proxy.content = c.proxy.content || {};
delete c.proxy.content[data.id];
Realtime.whenRealtimeSyncs(c.lm.realtime, function () {
addReminders(ctx, id, {
id: data.id,
start: 0
});
sendUpdate(ctx, c);
cb();
});
@ -706,13 +830,27 @@ ctx.calendars[channel] = {
var removeClient = function (ctx, cId) {
var idx = ctx.clients.indexOf(cId);
ctx.clients.splice(idx, 1);
Object.keys(ctx.calendars).forEach(function (id) {
var cal = ctx.calendars[id];
if (cal.stores.length !== 1 || cal.stores[0] !== 0 || !cal.tempId.length) { return; }
// This is a temp calendar: check if the closed tab had this calendar opened
var idx = cal.tempId.indexOf(cId);
if (idx !== -1) { cal.tempId.splice(idx, 1); }
if (!cal.tempId.length) {
cal.stores = [];
// Close calendar
closeCalendar(ctx, id);
}
});
};
Calendar.init = function (cfg, waitFor, emit) {
var calendar = {};
var store = cfg.store;
if (!store.loggedIn || !store.proxy.edPublic) { return; } // XXX logged in only?
//if (!store.loggedIn || !store.proxy.edPublic) { return; } // XXX logged in only? we should al least allow read-only for URL calendars
var ctx = {
loggedIn: store.loggedIn && store.proxy.edPublic,
store: store,
Store: cfg.Store,
pinPads: cfg.pinPads,
@ -721,7 +859,7 @@ ctx.calendars[channel] = {
emit: emit,
onReady: Util.mkEvent(true),
calendars: {},
clients: [],
clients: []
};
initializeCalendars(ctx, waitFor(function (err) {
@ -783,13 +921,21 @@ ctx.calendars[channel] = {
}
if (cmd === 'IMPORT') {
if (ctx.store.offline) { return void cb({error: 'OFFLINE'}); }
if (!ctx.loggedIn) { return void cb({error: 'NOT_LOGGED_IN'}); }
return void importCalendar(ctx, data, clientId, cb);
}
if (cmd === 'IMPORT_ICS') {
if (ctx.store.offline) { return void cb({error: 'OFFLINE'}); }
if (!ctx.loggedIn) { return void cb({error: 'NOT_LOGGED_IN'}); }
return void importICSCalendar(ctx, data, clientId, cb);
}
if (cmd === 'ADD') {
if (ctx.store.offline) { return void cb({error: 'OFFLINE'}); }
if (!ctx.loggedIn) { return void cb({error: 'NOT_LOGGED_IN'}); }
return void addCalendar(ctx, data, clientId, cb);
}
if (cmd === 'CREATE') {
if (!ctx.loggedIn) { return void cb({error: 'NOT_LOGGED_IN'}); }
if (data.initialCalendar) {
return void ctx.Store.onReadyEvt.reg(function () {
createCalendar(ctx, data, clientId, cb);
@ -800,22 +946,27 @@ ctx.calendars[channel] = {
}
if (cmd === 'UPDATE') {
if (ctx.store.offline) { return void cb({error: 'OFFLINE'}); }
if (!ctx.loggedIn) { return void cb({error: 'NOT_LOGGED_IN'}); }
return void updateCalendar(ctx, data, clientId, cb);
}
if (cmd === 'DELETE') {
if (ctx.store.offline) { return void cb({error: 'OFFLINE'}); }
if (!ctx.loggedIn) { return void cb({error: 'NOT_LOGGED_IN'}); }
return void deleteCalendar(ctx, data, clientId, cb);
}
if (cmd === 'CREATE_EVENT') {
if (ctx.store.offline) { return void cb({error: 'OFFLINE'}); }
if (!ctx.loggedIn) { return void cb({error: 'NOT_LOGGED_IN'}); }
return void createEvent(ctx, data, clientId, cb);
}
if (cmd === 'UPDATE_EVENT') {
if (ctx.store.offline) { return void cb({error: 'OFFLINE'}); }
if (!ctx.loggedIn) { return void cb({error: 'NOT_LOGGED_IN'}); }
return void updateEvent(ctx, data, clientId, cb);
}
if (cmd === 'DELETE_EVENT') {
if (ctx.store.offline) { return void cb({error: 'OFFLINE'}); }
if (!ctx.loggedIn) { return void cb({error: 'NOT_LOGGED_IN'}); }
return void deleteEvent(ctx, data, clientId, cb);
}
};

@ -40,6 +40,19 @@ define([
};
};
Block.keysToRPCFormat = function (keys) {
try {
var sign = keys.sign;
return {
edPrivate: Nacl.util.encodeBase64(sign.secretKey),
edPublic: Nacl.util.encodeBase64(sign.publicKey),
};
} catch (err) {
console.error(err);
return;
}
};
// (UTF8 content, keys object) => Uint8Array block
Block.encrypt = function (version, content, keys) {
var u8 = Nacl.util.decodeUTF8(content);
@ -86,6 +99,20 @@ define([
};
};
Block.proveAncestor = function (O /* oldBlockKeys */, N /* newBlockKeys */) {
N = N;
var u8_pub = Util.find(O, ['sign', 'publicKey']);
var u8_secret = Util.find(O, ['sign', 'secretKey']);
try {
// sign your old publicKey with your old privateKey
var u8_sig = Nacl.sign.detached(u8_pub, u8_secret);
// return an array with the sig and the pubkey
return JSON.stringify([u8_pub, u8_sig].map(Nacl.util.encodeBase64));
} catch (err) {
return void console.error(err);
}
};
Block.remove = function (keys) {
// sign the hash of the text 'DELETE_BLOCK'
var sig = Nacl.sign.detached(Nacl.hash(

@ -169,6 +169,18 @@ proxy.mailboxes = {
var dismiss = function (ctx, data, cId, cb) {
var type = data.type;
var hash = data.hash;
// Reminder messages don't persist
if (/^REMINDER\|/.test(hash)) {
cb();
delete ctx.boxes.reminders.content[hash];
hideMessage(ctx, type, hash, ctx.clients.filter(function (clientId) {
return clientId !== cId;
}));
return;
}
var box = ctx.boxes[type];
if (!box) { return void cb({error: 'NOT_LOADED'}); }
var m = box.data || {};
@ -488,7 +500,13 @@ proxy.mailboxes = {
msg: ctx.boxes[type].content[h],
hash: h
};
showMessage(ctx, type, message, cId);
showMessage(ctx, type, message, cId, function (obj) {
if (obj.error) { return; }
// Notify only if "requiresNotif" is true
if (!message.msg || !message.msg.requiresNotif) { return; }
Notify.system(undefined, obj.msg);
delete message.msg.requiresNotif;
});
});
});
// Subscribe to new notifications
@ -528,6 +546,10 @@ proxy.mailboxes = {
initializeHistory(ctx);
}
ctx.boxes.reminders = {
content: {}
};
Object.keys(mailboxes).forEach(function (key) {
if (TYPES.indexOf(key) === -1) { return; }
var m = mailboxes[key];
@ -568,6 +590,21 @@ proxy.mailboxes = {
});
};
mailbox.showMessage = function (type, msg, cId, cb) {
if (type === "reminders" && msg) {
ctx.boxes.reminders.content[msg.hash] = msg.msg;
if (!ctx.clients.length) {
ctx.boxes.reminders.content[msg.hash].requiresNotif = true;
}
// Hide existing messages for this event
hideMessage(ctx, type, msg.hash, ctx.clients);
}
showMessage(ctx, type, msg, cId, function (obj) {
Notify.system(undefined, obj.msg);
if (cb) { cb(); }
});
};
mailbox.open = function (key, m, cb, team, opts) {
if (TYPES.indexOf(key) === -1 && !team) { return; }
openChannel(ctx, key, m, cb, opts);

@ -226,11 +226,15 @@ var factory = function (Util, Rpc) {
console.log(data);
return void cb("MISSING_PARAMETERS");
}
if (['string', 'undefined'].indexOf(typeof(data.registrationProof)) === -1) {
return void cb("INVALID_REGISTRATION_PROOF");
}
rpc.send('WRITE_LOGIN_BLOCK', [
data.publicKey,
data.signature,
data.ciphertext
data.ciphertext,
data.registrationProof || undefined,
], function (e) {
cb(e);
});

@ -239,7 +239,7 @@ define([
if (!Env.folders[id]) { return {}; }
var obj = Env.folders[id].proxy.metadata || {};
for (var k in Env.user.proxy[UserObject.SHARED_FOLDERS][id] || {}) {
if (typeof(Env.user.proxy[UserObject.SHARED_FOLDERS][id][k]) === "undefined") {
if (typeof(Env.user.proxy[UserObject.SHARED_FOLDERS][id][k]) === "undefined") { // XXX "deleted folder" for restricted shared folders when viewer in a team
continue;
}
var data = Util.clone(Env.user.proxy[UserObject.SHARED_FOLDERS][id][k]);

@ -912,6 +912,9 @@ define([
var $copy = common.createButton('copy', true);
toolbar.$drawer.append($copy);
var $store = common.createButton('storeindrive', true);
toolbar.$drawer.append($store);
if (!cpNfInner.metadataMgr.getPrivateData().isTemplate) {
var templateObj = {
rt: cpNfInner.chainpad,

@ -129,7 +129,8 @@ define([
var l = privateData.plan ? ApiConfig.premiumUploadSize : false;
l = l || ApiConfig.maxUploadSize || "?";
var maxSizeStr = Util.bytesToMegabytes(l);
if (blob && blob.byteLength && typeof(l) === "number" && blob.byteLength > l) {
var estimate = FileCrypto.computeEncryptedSize((blob && blob.byteLength) || 0, metadata);
if (blob && blob.byteLength && typeof(estimate) === 'number' && typeof(l) === "number" && estimate > l) {
$pv.text(Messages.error);
queue.inProgress = false;
queue.next();

@ -65,6 +65,8 @@ define([
if (/^LOCAL\|/.test(data.content.hash)) {
$(avatar).addClass('preview');
}
} else if (data.type === 'reminders') {
avatar = h('i.fa.fa-calendar.cp-broadcast.preview');
} else if (userData && typeof(userData) === "object" && userData.profile) {
avatar = h('span.cp-avatar');
Common.displayAvatar($(avatar), userData.avatar, userData.displayName || userData.name);
@ -85,6 +87,15 @@ define([
if (typeof(data.content.getFormatText) === "function") {
$(notif).find('.cp-notification-content p').html(data.content.getFormatText());
if (data.content.autorefresh) {
var it = setInterval(function () {
if (!data.content.autorefresh) {
clearInterval(it);
return;
}
$(notif).find('.cp-notification-content p').html(data.content.getFormatText());
}, 60000);
}
}
if (data.content.isClickable) {
@ -117,7 +128,7 @@ define([
// Call the onMessage handlers
var isNotification = function (type) {
return type === "notifications" || /^team-/.test(type) || type === "broadcast";
return type === "notifications" || /^team-/.test(type) || type === "broadcast" || type === "reminders";
};
var pushMessage = function (data, handler) {
var todo = function (f) {

@ -626,7 +626,6 @@ define([
},
isNewFile: isNewFile,
isDeleted: isDeleted,
password: password,
channel: secret.channel,
enableSF: localStorage.CryptPad_SF === "1", // TODO to remove when enabled by default
devMode: localStorage.CryptPad_dev === "1",
@ -651,6 +650,7 @@ define([
if (isSafe) {
additionalPriv.hashes = hashes;
additionalPriv.password = password;
}
for (var k in additionalPriv) { metaObj.priv[k] = additionalPriv[k]; }

@ -1155,7 +1155,7 @@ MessengerUI, Messages, Pages) {
$button.addClass('fa-bell');
};
Common.mailbox.subscribe(['notifications', 'team', 'broadcast'], {
Common.mailbox.subscribe(['notifications', 'team', 'broadcast', 'reminders'], {
onMessage: function (data, el) {
if (el) {
$(div).prepend(el);

@ -30,10 +30,6 @@ define([
'css!/bower_components/codemirror/lib/codemirror.css',
'css!/bower_components/codemirror/addon/dialog/dialog.css',
'css!/bower_components/codemirror/addon/fold/foldgutter.css',
'css!/kanban/jkanban.css',
'less!/kanban/app-kanban.less'
], function (
$,

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

@ -0,0 +1,373 @@
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under this License. Except to the extent prohibited by statute
or regulation, such description must be sufficiently detailed for a
recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.

@ -0,0 +1 @@
`cryptpad/www/lib/ical.min.js` was imported from https://github.com/mozilla-comm/ical.js and is available under the terms of the Mozilla Public License Version 2.0, included in this folder.

@ -11,21 +11,11 @@ define([
'css!/bower_components/components-font-awesome/css/font-awesome.min.css',
], function ($, Cryptpad, Login, UI, Realtime, Feedback, LocalStore, Test) {
$(function () {
var $main = $('#mainBlock');
var $checkImport = $('#import-recent');
// main block is hidden in case javascript is disabled
$main.removeClass('hidden');
// Make sure we don't display non-translated content (empty button)
$main.find('#data').removeClass('hidden');
if (LocalStore.isLoggedIn()) {
// already logged in, redirect to drive
document.location.href = '/drive/';
return;
} else {
$main.find('#userForm').removeClass('hidden');
}
/* Log in UI */

@ -45,7 +45,7 @@ define([
'/customize/application_config.js',
'/common/test.js',
'/bower_components/diff-dom/diffDOM.js',
'/lib/diff-dom/diffDOM.js',
'/bower_components/file-saver/FileSaver.min.js',
'css!/customize/src/print.css',
@ -1448,7 +1448,6 @@ define([
editor.addCommand(tag, new CKEDITOR.styleCommand(new CKEDITOR.style({ element: tag })));
editor.setKeystroke( CKEDITOR.CTRL + CKEDITOR.ALT + styleKeys[tag], tag);
});
}).nThen(function() {
// Move ckeditor parts to have a structure like the other apps
var $contentContainer = $('#cke_1_contents');

@ -5,7 +5,7 @@ define([
'/customize/messages.js'
], function ($, h, UIElements, Messages) {
var onLinkClicked = function (e, inner, openLinkSetting) {
var onLinkClicked = function (e, inner, openLinkSetting, editor) {
var $target = $(e.target);
if (!$target.is('a')) {
$target = $target.closest('a');
@ -18,14 +18,20 @@ define([
e.preventDefault();
e.stopPropagation();
var open = function () {
if (href[0] === '#') {
var anchor = $inner.find(href);
if (!anchor.length) { return; }
anchor[0].scrollIntoView();
try {
$inner.find('.cke_anchor[data-cke-realelement]').each(function (j, el) {
var i = editor.restoreRealElement($(el));
var node = i.$;
if (node.id === href.slice(1)) {
el.scrollIntoView();
}
});
} catch (err) {}
return;
}
var open = function () {
var bounceHref = window.location.origin + '/bounce/#' + encodeURIComponent(href);
window.open(bounceHref);
};
@ -39,7 +45,9 @@ define([
var l = (rect.left - rect0.left)+'px';
var t = rect.bottom + $iframe.scrollTop() +'px';
var a = h('a', { href: href}, href);
var text = href;
if (text[0] === '#') { text = Messages.pad_goToAnchor; }
var a = h('a', { href: href}, text);
var link = h('div.cp-link-clicked.non-realtime', {
contenteditable: false,
style: 'top:'+t+';left:'+l
@ -76,7 +84,7 @@ define([
$inner.click(function (e) {
removeClickedLink($inner);
if (e.target.nodeName.toUpperCase() === 'A' || $(e.target).closest('a').length) {
return void onLinkClicked(e, inner, openLinkSetting);
return void onLinkClicked(e, inner, openLinkSetting, editor);
}
});

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save