diff --git a/.horde.yml b/.horde.yml
index d2cf3db50..e4e6551e5 100644
--- a/.horde.yml
+++ b/.horde.yml
@@ -66,6 +66,7 @@ dependencies:
horde/notification: ^3
horde/pack: ^2
horde/perms: ^3
+ horde/sasl: ^1
horde/spellchecker: ^3
horde/stream: ^2
horde/stream_filter: ^3
diff --git a/config/conf.xml b/config/conf.xml
index 4bcef2471..b45a49b1f 100644
--- a/config/conf.xml
+++ b/config/conf.xml
@@ -13,6 +13,17 @@
+ traditional
+
+
+
diff --git a/config/routes.php b/config/routes.php
index 4eca4d77b..891f41f20 100644
--- a/config/routes.php
+++ b/config/routes.php
@@ -1,3 +1,19 @@
buildRoute(uri: '/mailboxes/authtest', name: 'ImpAuthTest')
+ ->withController(\Horde\Imp\Mailboxes\AuthTestController::class)
+ ->withDefaults(['HordeAuthType' => 'authenticate'])
+ ->withMiddleware(DefaultStack::get())
+ ->add();
+
diff --git a/js/autocomplete.js b/js/autocomplete.js
index 832a82862..c799cc36a 100644
--- a/js/autocomplete.js
+++ b/js/autocomplete.js
@@ -15,127 +15,108 @@
* @copyright 2008-2015 Horde LLC
* @license GPL-2 (http://www.horde.org/licenses/gpl)
*/
-var IMP_Autocompleter = Class.create({
-
- // ac,
- // acTimeout,
- // box,
- // cache,
- // data,
- // dimg,
- // elt,
- // elt_ac,
- // input,
- // itemid,
- // knl,
- // knl_status,
- // lastinput,
- // p,
-
- initialize: function(elt, params)
- {
- var active;
-
- this.cache = $H();
- this.itemid = 0;
- this.lastinput = '';
- this.p = Object.extend({
- autocompleterParams: {},
- // Outer div/fake input box and CSS class
- // box (created below)
- boxClass: 'hordeACBox',
- boxClassFocus: '',
- entryDelay: 0.4,
- // CSS class for real input field
- growingInputClass: 'hordeACTrigger',
- // input, (created below)
- //
CSS class
- listClass: 'hordeACList',
- listClassItem: 'hordeACListItem',
- loadingText: 'Loading...',
- loadingTextClass: '',
- maxItemSize: 50,
- minChars: 3,
- noResultsText: 'No Results Found',
- noResultsTextClass: '',
- onAdd: Prototype.emptyFunction,
- onBeforeServerRequest: Prototype.emptyFunction,
- onEntryClick: Prototype.emptyFunction,
- onServerSuggestion: Prototype.emptyFunction,
- processValueCallback: Prototype.emptyFunction,
- removeClass: 'hordeACItemRemove',
- requireSelection: false,
- shortDisplayCallback: Prototype.K
- }, params || {});
-
- // The original input element is transformed into a hidden input
- // field that holds the raw return value.
- this.elt = $(elt);
- this.elt.writeAttribute('autocomplete', 'off');
-
- // Create an autocomplete input element that holds the JSON encoded
- // return value.
- this.elt_ac = new Element('INPUT', {
- name: this.elt.identify() + '_ac',
- type: 'hidden'
- });
- this.elt.insert({ after: this.elt_ac });
+var IMP_Autocompleter = function(elt, params) {
+ var active;
+
+ this.cache = $H();
+ this.itemid = 0;
+ this.lastinput = '';
+ this.p = Object.assign({
+ autocompleterParams: {},
+ // Outer div/fake input box and CSS class
+ // box (created below)
+ boxClass: 'hordeACBox',
+ boxClassFocus: '',
+ entryDelay: 0.4,
+ // CSS class for real input field
+ growingInputClass: 'hordeACTrigger',
+ // input, (created below)
+ // CSS class
+ listClass: 'hordeACList',
+ listClassItem: 'hordeACListItem',
+ loadingText: 'Loading...',
+ loadingTextClass: '',
+ maxItemSize: 50,
+ minChars: 3,
+ noResultsText: 'No Results Found',
+ noResultsTextClass: '',
+ onAdd: function() {},
+ onBeforeServerRequest: function() {},
+ onEntryClick: function() {},
+ onServerSuggestion: function() {},
+ processValueCallback: function() {},
+ removeClass: 'hordeACItemRemove',
+ requireSelection: false,
+ shortDisplayCallback: function(x) { return x; }
+ }, params || {});
+
+ // The original input element is transformed into a hidden input
+ // field that holds the raw return value.
+ this.elt = document.getElementById(elt);
+ this.elt.setAttribute('autocomplete', 'off');
+
+ // Create an autocomplete input element that holds the JSON encoded
+ // return value.
+ this.elt_ac = document.createElement('INPUT');
+ this.elt_ac.name = this.elt.id + '_ac';
+ this.elt_ac.type = 'hidden';
+ this.elt.after(this.elt_ac);
+
+ this.box = document.createElement('DIV');
+ this.box.className = this.p.boxClass;
+
+ // The input element and the - wrapper
+ this.input = document.createElement('INPUT');
+ this.input.autocomplete = 'off';
+ this.input.className = this.p.growingInputClass;
+
+ // Build the outer box
+ var ul = document.createElement('UL');
+ ul.className = this.p.listClass;
+ var li = document.createElement('LI');
+ li.appendChild(this.input);
+ ul.appendChild(li);
+ this.box.appendChild(ul);
+
+ // Replace the single input element with the new structure and
+ // move the old element into the structure while making sure it's
+ // hidden.
+ active = this.checkActiveElt(this.elt);
+ this.elt.replaceWith(this.box);
+ this.elt.hidden = true;
+ this.box.appendChild(this.elt);
+ if (active) {
+ this.focus();
+ }
- this.box = new Element('DIV', { className: this.p.boxClass });
+ // Look for clicks on the box to simulate clicking in an input box
+ this.box.addEventListener('click', this.clickHandler.bind(this));
- // The input element and the
- wrapper
- this.input = new Element('INPUT', {
- autocomplete: 'off',
- className: this.p.growingInputClass
- });
+ // Double-clicks cause an edit on existing entries.
+ this.box.addEventListener('dblclick', this.dblclickHandler.bind(this));
- // Build the outer box
- this.box.insert(
- // The list - where the chosen items are placed as
- nodes
- new Element('UL', { className: this.p.listClass }).insert(
- new Element('LI').insert(this.input)
- )
- );
-
- // Replace the single input element with the new structure and
- // move the old element into the structure while making sure it's
- // hidden.
- active = this.checkActiveElt(this.elt);
- this.box.insert(this.elt.replace(this.box).hide());
- if (active) {
- this.focus();
- }
+ this.input.addEventListener('blur', this.blur.bind(this));
+ this.input.addEventListener('keydown', this.keydownHandler.bind(this));
- // Look for clicks on the box to simulate clicking in an input box
- this.box.observe('click', this.clickHandler.bindAsEventListener(this));
+ this._watchInterval = setInterval(this.inputWatcher.bind(this), 250);
- // Double-clicks cause an edit on existing entries.
- this.box.observe('dblclick', this.dblclickHandler.bindAsEventListener(this));
+ document.addEventListener('AutoComplete:focus', this.triggerEvent.bind(this, this.focus.bind(this)));
+ document.addEventListener('AutoComplete:reset', this.triggerEvent.bind(this, this.reset.bind(this)));
+ document.addEventListener('AutoComplete:update', this.triggerEvent.bind(this, this.processInput.bind(this)));
- this.input.observe('blur', this.blur.bind(this));
- this.input.observe('keydown', this.keydownHandler.bindAsEventListener(this));
+ this.reset();
+};
- new PeriodicalExecuter(this.inputWatcher.bind(this), 0.25);
+IMP_Autocompleter.prototype = {
- document.observe('AutoComplete:focus', this.triggerEvent.bindAsEventListener(this, this.focus.bind(this)));
- document.observe('AutoComplete:reset', this.triggerEvent.bindAsEventListener(this, this.reset.bind(this)));
- document.observe('AutoComplete:update', this.triggerEvent.bindAsEventListener(this, this.processInput.bind(this)));
-
- this.reset();
- },
-
- triggerEvent: function(e, func)
+ triggerEvent: function(func, e)
{
- var elt = e.element();
-
- // IE 8 fix
- if (elt == window && elt.document) {
- elt = elt.document;
- }
+ var elt = e.target;
switch (elt) {
case this.elt:
- e.stop();
+ e.preventDefault();
+ e.stopPropagation();
/* falls through */
case document:
@@ -150,7 +131,6 @@ var IMP_Autocompleter = Class.create({
return (document.activeElement &&
(document.activeElement == elt));
} catch (e) {
- // IE 9 bug (activeElement can't be accessed via IFRAME)
return false;
}
},
@@ -159,32 +139,31 @@ var IMP_Autocompleter = Class.create({
{
try {
this.input.focus();
- this.box.addClassName(this.p.boxClassFocus);
+ this.box.classList.add(this.p.boxClassFocus);
} catch (e) {
- // IE8 bug (focus doesn't work on hidden fields)
- this.focus.bind(this).defer();
+ setTimeout(this.focus.bind(this), 0);
}
},
blur: function()
{
- this.box.removeClassName(this.p.boxClassFocus);
+ this.box.classList.remove(this.p.boxClassFocus);
},
reset: function()
{
this.data = [];
- this.currentEntries().invoke('remove');
- this.processValue($F(this.elt));
+ this.currentEntries().forEach(function(el) { el.remove(); });
+ this.processValue(this.elt.value);
this.processInput();
this.updateHiddenInput();
},
processInput: function()
{
- var tmp = $F(this.input);
+ var tmp = this.input.value;
- if (!tmp.empty()) {
+ if (tmp !== '') {
this.addNewItems([ new IMP_Autocompleter_Elt(tmp) ]);
this.updateInput('');
}
@@ -203,42 +182,49 @@ var IMP_Autocompleter = Class.create({
getElts: function()
{
- return this.data.pluck('elt');
+ return this.data.map(function(v) { return v.elt; });
},
getEntryByElt: function(elt)
{
- return this.getEntryById(elt.retrieve('itemid'));
+ return this.getEntryById(elt._itemid);
},
getEntryById: function(id)
{
- return this.data.detect(function(v) {
- return (v.id == id);
- });
+ for (var i = 0; i < this.data.length; i++) {
+ if (this.data[i].id == id) {
+ return this.data[i];
+ }
+ }
+ return null;
},
addNewItems: function(value)
{
value = this.filterChoices(value);
- if (!value.size()) {
+ if (!value.length) {
return false;
}
- value.each(function(v) {
- v.elt = new Element('LI', {
- className: this.p.listClassItem,
- title: v.label
- });
+ value.forEach(function(v) {
+ v.elt = document.createElement('LI');
+ v.elt.className = this.p.listClassItem;
+ v.elt.title = v.label;
v.id = ++this.itemid;
- this.input.up('LI').insert({ before:
- v.elt
- .insert((v.short_d || this.p.shortDisplayCallback(v.label)).truncate(this.p.maxItemSize).escapeHTML())
- .insert(this.deleteImg().clone(true).show())
- .store('itemid', v.id)
- });
+ var displayText = (v.short_d || this.p.shortDisplayCallback(v.label));
+ if (displayText.length > this.p.maxItemSize) {
+ displayText = displayText.substring(0, this.p.maxItemSize) + '...';
+ }
+ v.elt.appendChild(document.createTextNode(displayText));
+ var delImg = this.deleteImg().cloneNode(true);
+ delImg.hidden = false;
+ v.elt.appendChild(delImg);
+ v.elt._itemid = v.id;
+
+ this.input.closest('LI').before(v.elt);
this.data.push(v);
this.p.onAdd(v);
@@ -248,7 +234,7 @@ var IMP_Autocompleter = Class.create({
this.updateHiddenInput();
if (this.knl) {
- this.knl.hide();
+ this.knl.hide(); // eslint-disable-line horde/no-prototype-methods -- KeyNavList.hide()
}
return true;
@@ -256,29 +242,29 @@ var IMP_Autocompleter = Class.create({
filterChoices: function(c)
{
- var cv = this.data.pluck('value');
+ var cv = this.data.map(function(v) { return v.value; });
- return c.findAll(function(v) {
- return !cv.include(v.value);
+ return c.filter(function(v) {
+ return cv.indexOf(v.value) === -1;
});
},
currentEntries: function()
{
- return this.input.up('UL').select('LI.' + this.p.listClassItem);
+ return Array.from(this.input.closest('UL').querySelectorAll('LI.' + this.p.listClassItem));
},
updateInput: function(input)
{
var entry;
- if (Object.isElement(input)) {
+ if (input instanceof HTMLElement) {
entry = this.getEntryByElt(input);
- this.input.setValue(entry.value);
+ this.input.value = entry.value;
this.removeEntry(entry);
} else {
- if ($F(this.input) != input) {
- this.input.setValue(input);
+ if (this.input.value != input) {
+ this.input.value = input;
this.resize();
}
this.focus();
@@ -292,7 +278,7 @@ var IMP_Autocompleter = Class.create({
}
entry.elt.remove();
- this.data = this.data.findAll(function(v) {
+ this.data = this.data.filter(function(v) {
return (v.id != entry.id);
});
this.updateHiddenInput();
@@ -303,28 +289,26 @@ var IMP_Autocompleter = Class.create({
// AC Format: [ [ value, ID ], [ ... ], ... ]
updateHiddenInput: function()
{
- var val = this.data.pluck('value').without('');
+ var val = this.data.map(function(v) { return v.value; }).filter(function(v) { return v !== ''; });
- this.elt.setValue(val.join());
- this.elt_ac.setValue(Object.toJSON(val.zip(this.data.pluck('id'))));
+ this.elt.value = val.join();
+ this.elt_ac.value = JSON.stringify(val.map(function(v, i) { return [v, this.data[i].id]; }, this));
},
resize: function()
{
- this.input.setStyle({
- width: Math.max(80, $F(this.input).length * 9) + 'px'
- });
+ this.input.style.width = Math.max(80, this.input.value.length * 9) + 'px';
this.input.fire('AutoComplete:resize');
},
deleteImg: function()
{
if (!this.dimg) {
- this.dimg = new Element('IMG', {
- className: this.p.removeClass,
- src: this.p.deleteIcon
- }).hide();
- this.box.insert(this.dimg);
+ this.dimg = document.createElement('IMG');
+ this.dimg.className = this.p.removeClass;
+ this.dimg.src = this.p.deleteIcon;
+ this.dimg.hidden = true;
+ this.box.appendChild(this.dimg);
}
return this.dimg;
@@ -334,11 +318,11 @@ var IMP_Autocompleter = Class.create({
clickHandler: function(e)
{
- var elt = e.element(),
- li = elt.up('LI');
+ var elt = e.target,
+ li = elt.closest('LI');
if (!this.p.onEntryClick({ ac: this, elt: elt, entry: li })) {
- if (elt.hasClassName(this.p.removeClass)) {
+ if (elt.classList.contains(this.p.removeClass)) {
this.removeEntry(this.getEntryByElt(li));
}
}
@@ -348,11 +332,11 @@ var IMP_Autocompleter = Class.create({
dblclickHandler: function(e)
{
- var elt = e.findElement('LI');
+ var elt = e.target.closest('LI');
this.processInput();
- if (elt && elt.hasClassName(this.p.listClassItem)) {
+ if (elt && elt.classList.contains(this.p.listClassItem)) {
this.updateInput(elt);
} else {
this.focus();
@@ -363,13 +347,16 @@ var IMP_Autocompleter = Class.create({
{
var tmp;
- switch (e.which || e.keyCode || e.charCode) {
- case Event.KEY_DELETE:
- case Event.KEY_BACKSPACE:
- if (!$F(this.input).length &&
- (tmp = this.currentEntries().last())) {
- this.updateInput(tmp);
- e.stop();
+ switch (e.key) {
+ case 'Delete':
+ case 'Backspace':
+ if (!this.input.value.length) {
+ var entries = this.currentEntries();
+ tmp = entries.length ? entries[entries.length - 1] : null;
+ if (tmp) {
+ this.updateInput(tmp);
+ e.preventDefault();
+ }
}
break;
}
@@ -377,15 +364,15 @@ var IMP_Autocompleter = Class.create({
inputWatcher: function()
{
- var input = $F(this.input);
+ var input = this.input.value;
if (input != this.lastinput) {
this.processValue(input);
- this.lastinput = $F(this.input);
+ this.lastinput = this.input.value;
if (this.acTimeout) {
window.clearTimeout(this.acTimeout);
}
- this.acTimeout = this.doAutocomplete.bind(this, this.lastinput).delay(this.p.entryDelay);
+ this.acTimeout = setTimeout(this.doAutocomplete.bind(this, this.lastinput), this.p.entryDelay * 1000);
this.resize();
}
},
@@ -396,29 +383,29 @@ var IMP_Autocompleter = Class.create({
return;
}
- var c = this.cache.get(t), tmp;
+ var c = this.cache[t], tmp;
if (c) {
this.updateAutocomplete(t, c);
} else if (t.length >= this.p.minChars) {
tmp = this.p.onBeforeServerRequest(t, this.cache);
if (tmp) {
- this.cache.set(t, tmp);
+ this.cache[t] = tmp;
this.updateAutocomplete(t, tmp);
return;
}
this.initKnl();
this.knl_status = 'loading';
- this.knl.show([]);
+ this.knl.show([]); // eslint-disable-line horde/no-prototype-methods -- KeyNavList.show()
ImpCore.doAction(
'autocompleteSearch',
- Object.extend(this.p.autocompleterParams, { search: t }),
+ Object.assign(this.p.autocompleterParams, { search: t }),
{
callback: function(r, ajax) {
- this.cache.set(t, r.results);
- if (ajax.request.parameters.search == $F(this.input)) {
+ this.cache[t] = r.results;
+ if (ajax.request.parameters.search == this.input.value) {
this.updateAutocomplete(t, r.results);
}
}.bind(this)
@@ -440,28 +427,34 @@ var IMP_Autocompleter = Class.create({
return;
}
- r.each(function(e) {
+ r.forEach(function(e) {
var elt = new IMP_Autocompleter_Elt(e.v, e.l, e.s);
this.p.onServerSuggestion(e, elt);
obs.push(elt);
}, this);
obs = this.filterChoices(obs);
- if (obs.size()) {
+ if (obs.length) {
re = new RegExp(search, "i");
- obs.each(function(o) {
+ obs.forEach(function(o) {
var l = o.label,
l2 = '';
- (l.match(re) || []).each(function(m2) {
- var idx = l.indexOf(m2);
- l2 += l.substr(0, idx).escapeHTML() + "" + m2.escapeHTML() + "";
+ (l.match(re) || []).forEach(function(m2) {
+ var idx = l.indexOf(m2),
+ tmp = document.createElement('span');
+ tmp.textContent = l.substr(0, idx);
+ l2 += tmp.innerHTML + "";
+ tmp.textContent = m2;
+ l2 += tmp.innerHTML + "";
l = l.substr(idx + m2.length);
});
if (l.length) {
- l2 += l.escapeHTML();
+ var tmp = document.createElement('span');
+ tmp.textContent = l;
+ l2 += tmp.innerHTML;
}
c.push({ l: l2, v: o });
@@ -473,7 +466,7 @@ var IMP_Autocompleter = Class.create({
}
this.initKnl();
- this.knl.show(c);
+ this.knl.show(c); // eslint-disable-line horde/no-prototype-methods -- KeyNavList.show()
},
initKnl: function()
@@ -488,19 +481,17 @@ var IMP_Autocompleter = Class.create({
onShow: function(elt) {
switch (this.knl_status) {
case 'loading':
- elt.down().insert(
- new Element('LI').insert(
- this.p.loadingText.escapeHTML()
- ).addClassName(this.p.loadingTextClass)
- );
+ var loadLi = document.createElement('LI');
+ loadLi.textContent = this.p.loadingText;
+ loadLi.className = this.p.loadingTextClass;
+ elt.querySelector(':first-child').appendChild(loadLi);
break;
case 'noresults':
- elt.down().insert(
- new Element('LI').insert(
- this.p.noResultsText.escapeHTML()
- ).addClassName(this.p.noResultsTextClass)
- );
+ var noLi = document.createElement('LI');
+ noLi.textContent = this.p.noResultsText;
+ noLi.className = this.p.noResultsTextClass;
+ elt.querySelector(':first-child').appendChild(noLi);
break;
}
}.bind(this)
@@ -508,23 +499,12 @@ var IMP_Autocompleter = Class.create({
}
}
-}),
-
-IMP_Autocompleter_Elt = Class.create({
-
- // elt,
- // id,
- // label,
- // short_d,
- // value,
+};
- initialize: function(value, label, short_d)
- {
- this.value = value;
- this.label = label || value;
- if (short_d) {
- this.short_d = short_d;
- }
+var IMP_Autocompleter_Elt = function(value, label, short_d) {
+ this.value = value;
+ this.label = label || value;
+ if (short_d) {
+ this.short_d = short_d;
}
-
-});
+};
diff --git a/js/contacts.js b/js/contacts.js
index 33a056b4b..f847c862b 100644
--- a/js/contacts.js
+++ b/js/contacts.js
@@ -14,38 +14,38 @@ var ImpContacts = {
selectedAddresses: function()
{
- return $('selected_addresses').select('[value]');
+ return Array.from(document.getElementById('selected_addresses').querySelectorAll('[value]'));
},
addAddress: function(f)
{
var df = document.createDocumentFragment(),
sa = this.selectedAddresses(),
- sr = $('search_results'),
- sel = $F(sr);
+ sr = document.getElementById('search_results'),
+ sel = Array.from(sr.selectedOptions).map(function(o) { return o.value; });
- if (!sel.size()) {
+ if (!sel.length) {
HordeCore.notify(this.text.select, 'horde.warning');
return;
}
- sel.each(function(s) {
- if (!sa.any(function(j) {
- return (j.readAttribute('value') == s) &&
- (j.retrieve('header') == f);
+ sel.forEach(function(s) {
+ if (!sa.some(function(j) {
+ return (j.getAttribute('value') == s) &&
+ (j._header == f);
})) {
- df.appendChild(
- new Element('OPTION', { value: s })
- .store('header', f)
- .insert(
- new Element('EM').insert(this.text.rcpt[f] + ': ')
- )
- .insert(s.escapeHTML())
- );
+ var opt = document.createElement('OPTION');
+ opt.value = s;
+ opt._header = f;
+ var em = document.createElement('EM');
+ em.textContent = this.text.rcpt[f] + ': ';
+ opt.appendChild(em);
+ opt.appendChild(document.createTextNode(s));
+ df.appendChild(opt);
}
}, this);
- $('selected_addresses').appendChild(df);
+ document.getElementById('selected_addresses').appendChild(df);
},
updateMessage: function()
@@ -59,19 +59,19 @@ var ImpContacts = {
return;
}
- if (!sa.size()) {
+ if (!sa.length) {
HordeCore.notify(this.text.no_contacts_selected, 'horde.warning');
return;
}
- sa.each(function(s) {
- var field = s.retrieve('header');
+ sa.forEach(function(s) {
+ var field = s._header;
- if (Object.isUndefined(addr[field])) {
+ if (typeof addr[field] === 'undefined') {
addr[field] = [];
}
- addr[field].push(s.readAttribute('value'));
+ addr[field].push(s.getAttribute('value'));
});
$(parent.opener.document).fire('ImpContacts:update', addr);
@@ -80,7 +80,7 @@ var ImpContacts = {
removeAddress: function()
{
- $('selected_addresses').childElements().each(function(o) {
+ Array.from(document.getElementById('selected_addresses').children).forEach(function(o) {
if (o.selected) {
o.remove();
}
@@ -89,21 +89,22 @@ var ImpContacts = {
contactsSearch: function()
{
- var sr = $('search_results');
+ var sr = document.getElementById('search_results');
- sr.select('[value]').invoke('remove');
- sr.childElements().invoke('hide');
- sr.appendChild(
- new Element('OPTION', { disabled: true, value: "" })
- .insert(this.text.searching)
- );
+ Array.from(sr.querySelectorAll('[value]')).forEach(function(o) { o.remove(); });
+ Array.from(sr.children).forEach(function(o) { o.hidden = true; });
+ var opt = document.createElement('OPTION');
+ opt.disabled = true;
+ opt.value = "";
+ opt.textContent = this.text.searching;
+ sr.appendChild(opt);
HordeCore.doAction('contactsSearch', {
- search: this.searchGhost.hasinput ? $F('search') : '',
- source: $F('source')
+ search: this.searchGhost.hasinput ? document.getElementById('search').value : '',
+ source: document.getElementById('source').value
}, {
callback: function(r) {
- sr.select(':not([value])').invoke('show');
+ Array.from(sr.querySelectorAll(':not([value])')).forEach(function(o) { o.hidden = false; });
this.updateResults(r.results);
}.bind(this)
});
@@ -112,18 +113,18 @@ var ImpContacts = {
updateResults: function(r)
{
var df = document.createDocumentFragment(),
- sr = $('search_results');
+ sr = document.getElementById('search_results');
- r.each(function(addr) {
- df.appendChild(
- new Element('OPTION', { value: addr })
- .insert(addr.escapeHTML())
- );
+ r.forEach(function(addr) {
+ var opt = document.createElement('OPTION');
+ opt.value = addr;
+ opt.textContent = addr;
+ df.appendChild(opt);
});
- sr.select('[value]').invoke('remove');
+ Array.from(sr.querySelectorAll('[value]')).forEach(function(o) { o.remove(); });
- if (r.size()) {
+ if (r.length) {
sr.appendChild(df);
}
},
@@ -132,7 +133,7 @@ var ImpContacts = {
{
window.resizeBy(
0,
- Math.max(0, document.body.clientHeight - document.viewport.getHeight())
+ Math.max(0, document.body.clientHeight - document.documentElement.clientHeight)
);
},
@@ -141,7 +142,7 @@ var ImpContacts = {
HordeCore.initHandler('click');
HordeCore.initHandler('dblclick');
- $('contacts').observe('FormGhost:submit', function(e) {
+ document.getElementById('contacts').addEventListener('FormGhost:submit', function(e) {
if (this.searchGhost.hasinput) {
this.contactsSearch();
}
@@ -154,12 +155,14 @@ var ImpContacts = {
this.searchGhost = new FormGhost('search');
- this.resize.bind(this).delay(0.1);
+ setTimeout(this.resize.bind(this), 100);
},
clickHandler: function(e)
{
- switch (e.element().readAttribute('id')) {
+ var id = e.target.id || (e.target.closest('[id]') || {}).id;
+
+ switch (id) {
case 'btn_add_bcc':
this.addAddress('bcc');
break;
@@ -174,7 +177,7 @@ var ImpContacts = {
case 'btn_cancel':
window.close();
- e.memo.hordecore_stop = true;
+ e.detail.hordecore_stop = true;
break;
case 'btn_clear':
@@ -186,7 +189,7 @@ var ImpContacts = {
break;
case 'btn_search_all':
- $('search').value = '';
+ document.getElementById('search').value = '';
this.contactsSearch();
break;
@@ -198,7 +201,9 @@ var ImpContacts = {
dblclickHandler: function(e)
{
- switch (e.element().readAttribute('id')) {
+ var id = e.target.id || (e.target.closest('[id]') || {}).id;
+
+ switch (id) {
case 'search_results':
this.addAddress('to');
break;
@@ -211,6 +216,6 @@ var ImpContacts = {
};
-document.observe('dom:loaded', ImpContacts.onDomLoad.bind(ImpContacts));
-document.observe('HordeCore:click', ImpContacts.clickHandler.bindAsEventListener(ImpContacts));
-document.observe('HordeCore:dblclick', ImpContacts.dblclickHandler.bindAsEventListener(ImpContacts));
+document.addEventListener('DOMContentLoaded', ImpContacts.onDomLoad.bind(ImpContacts));
+document.addEventListener('HordeCore:click', ImpContacts.clickHandler.bind(ImpContacts));
+document.addEventListener('HordeCore:dblclick', ImpContacts.dblclickHandler.bind(ImpContacts));
diff --git a/js/draghandler.js b/js/draghandler.js
index 48c9728bf..bcf5e5a91 100644
--- a/js/draghandler.js
+++ b/js/draghandler.js
@@ -1,5 +1,5 @@
/**
- * DragHandler library for use with prototypejs.
+ * DragHandler library.
*
* @author Michael Slusarz
* @copyright 2013-2015 Horde LLC
@@ -19,7 +19,7 @@ var DragHandler = {
{
return (e.dataTransfer &&
e.dataTransfer.types &&
- $A(e.dataTransfer.types).include('Files') &&
+ Array.from(e.dataTransfer.types).indexOf('Files') !== -1 &&
((e.type != 'drop') || e.dataTransfer.files.length));
},
@@ -27,25 +27,20 @@ var DragHandler = {
{
if (this.dropelt &&
(e.dataTransfer ||
- (e.memo && e.memo.dataTransfer) ||
- this.dropelt.visible())) {
- if (Prototype.Browser.IE &&
- !(("onpropertychange" in document) && (!!window.matchMedia))) {
- // IE 9 supports drag/drop, but not dataTransfer.files
- } else {
- switch (e.type) {
- case 'dragleave':
- this.handleLeave();
- break;
-
- case 'dragover':
- this.handleOver(e);
- break;
-
- case 'drop':
- this.handleDrop(e);
- break;
- }
+ (e.detail && e.detail.dataTransfer) ||
+ !this.dropelt.hidden)) {
+ switch (e.type) {
+ case 'dragleave':
+ this.handleLeave();
+ break;
+
+ case 'dragover':
+ this.handleOver(e);
+ break;
+
+ case 'drop':
+ this.handleDrop(e);
+ break;
}
}
},
@@ -53,23 +48,23 @@ var DragHandler = {
handleDrop: function(e)
{
this.leave = true;
- this.hide();
+ this.hide(); // eslint-disable-line horde/no-prototype-methods -- DragHandler.hide()
if (this.isFileDrag(e)) {
- if (this.dropelt.hasClassName(this.hoverclass)) {
+ if (this.dropelt.classList.contains(this.hoverclass)) {
this.dropelt.fire('DragHandler:drop', e.dataTransfer.files);
}
- e.stop();
- } else if (!e.findElement('TEXTAREA') && !e.findElement('INPUT')) {
- e.stop();
+ e.preventDefault();
+ } else if (!e.target.closest('TEXTAREA') && !e.target.closest('INPUT')) {
+ e.preventDefault();
}
},
hide: function()
{
if (this.leave) {
- this.dropelt.hide();
- this.droptarget.show();
+ this.dropelt.hidden = true;
+ this.droptarget.hidden = false;
this.leave = false;
}
},
@@ -77,7 +72,7 @@ var DragHandler = {
handleLeave: function()
{
clearTimeout(this.to);
- this.to = this.hide.bind(this).delay(0.25);
+ this.to = setTimeout(this.hide.bind(this), 250);
this.leave = true;
},
@@ -85,27 +80,30 @@ var DragHandler = {
{
var file = this.isFileDrag(e);
- if (file && !this.dropelt.visible()) {
- this.dropelt.clonePosition(this.droptarget).show();
- this.droptarget.hide();
+ if (file && this.dropelt.hidden) {
+ // Position dropelt over droptarget
+ var rect = this.droptarget.getBoundingClientRect();
+ this.dropelt.style.position = 'absolute';
+ this.dropelt.style.left = rect.left + 'px';
+ this.dropelt.style.top = rect.top + 'px';
+ this.dropelt.style.width = rect.width + 'px';
+ this.dropelt.style.height = rect.height + 'px';
+ this.dropelt.hidden = false;
+ this.droptarget.hidden = true;
}
this.leave = false;
if (file && (e.target == this.dropelt)) {
- this.dropelt.addClassName(this.hoverclass);
- e.stop();
+ this.dropelt.classList.add(this.hoverclass);
+ e.preventDefault();
} else {
- this.dropelt.removeClassName(this.hoverclass);
- if (Prototype.Browser.IE ||
- Prototype.Browser.Gecko) {
- e.stop();
- }
+ this.dropelt.classList.remove(this.hoverclass);
}
}
};
-document.observe('dragleave', DragHandler.handleObserve.bindAsEventListener(DragHandler));
-document.observe('dragover', DragHandler.handleObserve.bindAsEventListener(DragHandler));
-document.observe('drop', DragHandler.handleObserve.bindAsEventListener(DragHandler));
+document.addEventListener('dragleave', DragHandler.handleObserve.bind(DragHandler));
+document.addEventListener('dragover', DragHandler.handleObserve.bind(DragHandler));
+document.addEventListener('drop', DragHandler.handleObserve.bind(DragHandler));
diff --git a/js/editor.js b/js/editor.js
index 1da4c8593..5a365d532 100644
--- a/js/editor.js
+++ b/js/editor.js
@@ -6,43 +6,36 @@
* @license GPL-2 (http://www.horde.org/licenses/gpl)
*/
-var IMP_Editor = Class.create({
+var IMP_Editor = function(id, config) {
+ this.config = Object.assign({}, config);
+ this.id = id;
- // config,
- // dready,
- // editor,
- // id,
- // iready
- // wait,
+ this.start();
- initialize: function(id, config)
- {
- this.config = Object.clone(config);
- this.id = id;
-
- this.start();
+ this.editor.on('instanceReady', function(evt) {
+ this.iready = true;
+ document.fire('IMP_Editor:ready', evt.editor);
+ }.bind(this));
+ this.editor.on('dataReady', function(evt) {
+ if (!this.dready) {
+ document.fire('IMP_Editor:dataReady', evt.editor);
+ this.dready = true;
+ }
+ }.bind(this));
+ this.editor.on('instanceDestroyed', function(evt) {
+ this.dready = this.iready = this.editor = false;
+ document.fire('IMP_Editor:destroy', evt.editor);
+ }.bind(this));
+};
- this.editor.on('instanceReady', function(evt) {
- this.iready = true;
- document.fire('IMP_Editor:ready', evt.editor);
- }.bind(this));
- this.editor.on('dataReady', function(evt) {
- if (!this.dready) {
- document.fire('IMP_Editor:dataReady', evt.editor);
- this.dready = true;
- }
- }.bind(this));
- this.editor.on('instanceDestroyed', function(evt) {
- this.dready = this.iready = this.editor = false;
- document.fire('IMP_Editor:destroy', evt.editor);
- }.bind(this));
- },
+IMP_Editor.prototype = {
start: function()
{
if (!this.editor) {
- if (Object.isUndefined(this.config.height)) {
- this.config.height = Math.max($(this.id).getHeight(), 200) - 75;
+ if (typeof this.config.height === 'undefined') {
+ var elt = document.getElementById(this.id);
+ this.config.height = Math.max(elt.offsetHeight, 200) - 75;
}
this.editor = CKEDITOR.replace(this.id, this.config);
}
@@ -68,7 +61,7 @@ var IMP_Editor = Class.create({
setData: function(data)
{
if (this.busy()) {
- this.setData.bind(this, data).delay(0.1);
+ setTimeout(this.setData.bind(this, data), 100);
} else {
this.wait = true;
this.editor.setData(data, function() {
@@ -80,7 +73,7 @@ var IMP_Editor = Class.create({
resize: function(width, height)
{
if (this.busy()) {
- this.resize.bind(this, width, height).delay(0.1);
+ setTimeout(this.resize.bind(this, width, height), 100);
} else {
this.editor.resize(width, height);
}
@@ -89,7 +82,7 @@ var IMP_Editor = Class.create({
focus: function()
{
if (this.busy()) {
- this.focus.bind(this).delay(0.1);
+ setTimeout(this.focus.bind(this), 100);
} else {
this.editor.focus();
}
@@ -98,10 +91,10 @@ var IMP_Editor = Class.create({
updateElement: function()
{
if (this.busy()) {
- this.updateElement.bind(this).delay(0.1);
+ setTimeout(this.updateElement.bind(this), 100);
} else {
this.editor.updateElement();
}
}
-});
+};
diff --git a/js/imp.js b/js/imp.js
index a9caa40fa..f856506a1 100644
--- a/js/imp.js
+++ b/js/imp.js
@@ -19,42 +19,40 @@ var IMP_JS = {
unblockImages: function(e)
{
var a, callback, doc,
- elt = e.element(),
- box = elt.up('.mimeStatusMessageTable').up(),
- iframe = elt.up('.mimePartBase').down('.mimePartData IFRAME.htmlMsgData');
+ elt = e.target,
+ box = elt.closest('.mimeStatusMessageTable').parentElement,
+ iframe = elt.closest('.mimePartBase').querySelector('.mimePartData IFRAME.htmlMsgData');
- e.stop();
+ e.preventDefault();
- if (elt.readAttribute('noUnblockImageAdd')) {
- box.slideUp({
- afterFinish: function() { box.remove(); },
- duration: 0.6
- });
+ if (elt.getAttribute('noUnblockImageAdd')) {
+ box.hidden = true;
+ box.remove();
} else {
- a = new Element('A')
- .insert(IMP_JS.unblock_image_text)
- .observe('click', function() {
- HordeCore.doAction('imageUnblockAdd', {
- muid: elt.readAttribute('muid')
- });
-
- box.slideUp({
- afterFinish: function() { box.remove(); },
- duration: 0.6
- });
+ a = document.createElement('A');
+ a.textContent = IMP_JS.unblock_image_text;
+ a.addEventListener('click', function() {
+ HordeCore.doAction('imageUnblockAdd', {
+ muid: elt.getAttribute('muid')
});
- elt.up('TBODY').update(
- new Element('TR').insert(
- new Element('TD').insert(a)
- )
- );
+ box.hidden = true;
+ box.remove();
+ });
+
+ var tbody = elt.closest('TBODY');
+ var tr = document.createElement('TR');
+ var td = document.createElement('TD');
+ td.appendChild(a);
+ tr.appendChild(td);
+ tbody.innerHTML = '';
+ tbody.appendChild(tr);
}
callback = this.iframeResize.bind(this, iframe);
doc = this.iframeDoc(iframe);
- Prototype.Selector.select('[htmlimgblocked]', doc).each(function(img) {
+ doc.querySelectorAll('[htmlimgblocked]').forEach(function(img) {
var src = img.getAttribute('htmlimgblocked');
img.removeAttribute('htmlimgblocked');
@@ -69,24 +67,23 @@ var IMP_JS = {
if (img.style.setProperty) {
img.style.setProperty('background-image', 'url(' + src + ')', '');
} else {
- // IE workaround
img.style.backgroundImage = 'url(' + src + ')';
}
}
}
- }, this);
+ });
- Prototype.Selector.select('[htmlimgblocked_srcset]', doc).each(function(img) {
+ doc.querySelectorAll('[htmlimgblocked_srcset]').forEach(function(img) {
img.setAttribute('srcset', img.getAttribute('htmlimgblocked_srcset'));
img.removeAttribute('htmlimgblocked_srcset');
});
- Prototype.Selector.select('[htmlcssblocked]', doc).each(function(link) {
+ doc.querySelectorAll('[htmlcssblocked]').forEach(function(link) {
link.setAttribute('href', link.getAttribute('htmlcssblocked'));
link.removeAttribute('htmlcssblocked');
});
- Prototype.Selector.select('STYLE[type="text/x-imp-cssblocked"]', doc).each(function(style) {
+ doc.querySelectorAll('STYLE[type="text/x-imp-cssblocked"]').forEach(function(style) {
style.setAttribute('type', 'text/css');
});
@@ -95,7 +92,10 @@ var IMP_JS = {
iframeInject: function(id, data)
{
- if (!(id = $(id))) {
+ if (typeof id === 'string') {
+ id = document.getElementById(id);
+ }
+ if (!id) {
return;
}
@@ -111,31 +111,27 @@ var IMP_JS = {
d.close();
ev = function(name, e) {
- id.fire('IMP_JS:' + name, e);
+ $(id).fire('IMP_JS:' + name, e);
};
- if (d.addEventListener) {
- d.addEventListener('click', ev.curry('htmliframe_click'), false);
- d.addEventListener('keydown', ev.curry('htmliframe_keydown'), false);
- } else {
- d.attachEvent('onclick', ev.curry('htmliframe_click'));
- d.attachEvent('onkeydown', ev.curry('htmliframe_keydown'));
- }
+ d.addEventListener('click', ev.bind(null, 'htmliframe_click'), false);
+ d.addEventListener('keydown', ev.bind(null, 'htmliframe_keydown'), false);
this.iframeOverflowY(id, false);
- id.show().previous().remove();
+ id.hidden = false;
+ var prev = id.previousElementSibling;
+ if (prev) { prev.remove(); }
this.iframeResize(id);
},
// iframe = (Element)
iframeResize: function(iframe)
{
- var id = iframe.identify();
+ var id = iframe.id || (iframe.id = 'horde_' + Date.now());
- // IE (at a minimum) needs a slight delay to size properly
if (!this.iframeresize_run[id]) {
this.iframeresize_run[id] = true;
- this.iframeResizeRun.bind(this, iframe).delay(this.resize_delay);
+ setTimeout(this.iframeResizeRun.bind(this, iframe), this.resize_delay * 1000);
}
},
@@ -145,7 +141,8 @@ var IMP_JS = {
doc = this.iframeDoc(id);
if (!doc) {
- this.iframeresize_run[id.identify()] = false;
+ var eid = id.id || (id.id = 'horde_' + Date.now());
+ this.iframeresize_run[eid] = false;
return;
}
@@ -154,36 +151,35 @@ var IMP_JS = {
iHeight = function() {
return Math.max(
body.offsetHeight,
- // IE 8 only
- (Prototype.Browser.IE && !document.addEventListener) ? body.scrollHeight : 0,
html.offsetHeight,
html.scrollHeight
);
};
- Element.setStyle(body, { height: null });
+ body.style.height = '';
h1 = iHeight();
- id.setStyle({ height: h1 + 'px' });
+ id.style.height = h1 + 'px';
h2 = iHeight();
if (h2 > h1) {
- id.setStyle({ height: h2 + 'px' });
+ id.style.height = h2 + 'px';
}
this.iframeImgLazyLoad(id);
- this.iframeresize_run[id.identify()] = false;
+ var eid2 = id.id || (id.id = 'horde_' + Date.now());
+ this.iframeresize_run[eid2] = false;
},
iframeImgLazyLoad: function(iframe)
{
- var id = iframe.identify();
+ var id = iframe.id || (iframe.id = 'horde_' + Date.now());
if (!this.lazyload_run[id]) {
this.lazyload_run[id] = true;
- this.iframeImgLazyLoadRun.bind(this, iframe)
- .delay(this.resize_delay);
+ setTimeout(this.iframeImgLazyLoadRun.bind(this, iframe),
+ this.resize_delay * 1000);
}
},
@@ -194,19 +190,22 @@ var IMP_JS = {
mb = this.messageBody();
if (!doc) {
- this.lazyload_run[iframe.identify()] = false;
+ var eid = iframe.id || (iframe.id = 'horde_' + Date.now());
+ this.lazyload_run[eid] = false;
return;
}
/* Load messages within 1 scrolled page of range boundaries. */
- mb_height = mb.getHeight();
+ mb_height = mb.offsetHeight;
range_top = mb.scrollTop - mb_height;
range_bottom = mb.scrollTop + (2 * mb_height);
- imgs = Prototype.Selector.select('IMG[data-src]', doc).findAll(Element.visible);
+ imgs = Array.from(doc.querySelectorAll('IMG[data-src]')).filter(function(img) {
+ return !img.hidden && img.offsetWidth > 0;
+ });
- if (imgs.size()) {
- iframe.setStyle({ overflowY: 'hidden' });
+ if (imgs.length) {
+ iframe.style.overflowY = 'hidden';
error = this.iframeOverflowY.bind(this, iframe);
resize = function() {
@@ -214,19 +213,21 @@ var IMP_JS = {
this.iframeOverflowY(iframe, true);
}.bind(this);
- imgs.each(function(img) {
- var co = Element.cumulativeOffset(img);
- if (co.top > range_top && co.top < range_bottom) {
+ imgs.forEach(function(img) {
+ var rect = img.getBoundingClientRect();
+ var co_top = rect.top + (doc.defaultView ? doc.defaultView.pageYOffset : 0);
+ if (co_top > range_top && co_top < range_bottom) {
this.iframeOverflowY(iframe, false);
img.onerror = error;
img.onload = resize;
- Element.writeAttribute(img, 'src', Element.readAttribute(img, 'data-src'));
- Element.writeAttribute(img, 'data-src', null);
+ img.setAttribute('src', img.getAttribute('data-src'));
+ img.removeAttribute('data-src');
}
}, this);
}
- this.lazyload_run[iframe.identify()] = false;
+ var eid2 = iframe.id || (iframe.id = 'horde_' + Date.now());
+ this.lazyload_run[eid2] = false;
},
iframeDoc: function(i)
@@ -237,18 +238,18 @@ var IMP_JS = {
iframeOverflowY: function(id, show)
{
- var key = id.identify();
+ var key = id.id || (id.id = 'horde_' + Date.now());
if (show) {
if (this.iframe_y[key] && !(--this.iframe_y[key])) {
- id.setStyle({ overflowY: '' });
+ id.style.overflowY = '';
delete this.iframe_y[key];
}
} else {
if (this.iframe_y[key]) {
++this.iframe_y[key];
} else {
- id.setStyle({ overflowY: 'hidden' });
+ id.style.overflowY = 'hidden';
this.iframe_y[key] = 1;
}
}
@@ -256,14 +257,14 @@ var IMP_JS = {
messageBody: function()
{
- return $('previewPane') || $('messageBody');
+ return document.getElementById('previewPane') || document.getElementById('messageBody');
},
printWindow: function(win)
{
win.print();
// Bug #12833: Fixes closing print window in Chrome.
- (function() { win.close(); }).defer();
+ setTimeout(function() { win.close(); }, 0);
},
resizePopup: function(win)
@@ -304,12 +305,12 @@ var IMP_JS = {
var mb = this.messageBody();
if (mb) {
- mb.observe('scroll', function() {
- $('messageBody').select('IFRAME.htmlMsgData').each(this.iframeImgLazyLoad.bind(this));
+ mb.addEventListener('scroll', function() {
+ Array.from(document.getElementById('messageBody').querySelectorAll('IFRAME.htmlMsgData')).forEach(this.iframeImgLazyLoad.bind(this));
}.bind(this));
}
}
};
-document.observe('dom:loaded', IMP_JS.onDomLoad.bind(IMP_JS));
+document.addEventListener('DOMContentLoaded', IMP_JS.onDomLoad.bind(IMP_JS));
diff --git a/js/login.js b/js/login.js
index a9f91f20f..25ac10692 100644
--- a/js/login.js
+++ b/js/login.js
@@ -6,12 +6,15 @@
* @license GPL-2 (http://www.horde.org/licenses/gpl)
*/
-HordeLogin.submit = HordeLogin.submit.wrap(function(parentfunc) {
- var k = $('imp_server_key');
- if (k && $F(k).startsWith('_')) {
- alert(HordeLogin.server_key_error);
- k.focus();
- } else {
- parentfunc();
- }
-});
+(function() {
+ var origSubmit = HordeLogin.submit;
+ HordeLogin.submit = function() {
+ var k = document.getElementById('imp_server_key');
+ if (k && k.value.startsWith('_')) {
+ alert(HordeLogin.server_key_error);
+ k.focus();
+ } else {
+ origSubmit.call(HordeLogin);
+ }
+ };
+})();
diff --git a/js/maillog.js b/js/maillog.js
index bc543afcd..fff1fe899 100644
--- a/js/maillog.js
+++ b/js/maillog.js
@@ -19,11 +19,13 @@ var ImpMaillog = {
base.HordeCore.notify(this.error_msg, 'horde.error');
window.close();
} else {
- document.body.insert(this.error_msg.escapeHTML());
+ var tmp = document.createElement('SPAN');
+ tmp.textContent = this.error_msg;
+ document.body.appendChild(tmp);
}
}
};
/* Initialize onload handler. */
-document.observe('dom:loaded', ImpMaillog.onDomLoad.bind(ImpMaillog));
+document.addEventListener('DOMContentLoaded', ImpMaillog.onDomLoad.bind(ImpMaillog));
diff --git a/js/message.js b/js/message.js
index a7ff3c52e..64c04e75f 100644
--- a/js/message.js
+++ b/js/message.js
@@ -22,8 +22,8 @@ var ImpMessage = {
case 'reply_all':
case 'reply_auto':
case 'reply_list':
- $('compose').show();
- $('redirect').hide();
+ document.getElementById('compose').hidden = false;
+ document.getElementById('redirect').hidden = true;
func = 'getReplyData';
break;
@@ -31,30 +31,30 @@ var ImpMessage = {
case 'forward_attach':
case 'forward_body':
case 'forward_both':
- $('compose').show();
- $('redirect').hide();
+ document.getElementById('compose').hidden = false;
+ document.getElementById('redirect').hidden = true;
func = 'getForwardData';
break;
case 'forward_editasnew':
- $('compose').show();
- $('redirect').hide();
+ document.getElementById('compose').hidden = false;
+ document.getElementById('redirect').hidden = true;
func = 'getResumeData';
type = 'editasnew';
break;
case 'forward_redirect':
- $('compose').hide();
- $('redirect').show();
+ document.getElementById('compose').hidden = true;
+ document.getElementById('redirect').hidden = false;
func = 'getRedirectData';
break;
}
- $('msgData').hide();
- $('qreply').show();
+ document.getElementById('msgData').hidden = true;
+ document.getElementById('qreply').hidden = false;
ImpCore.doAction(func, {
- imp_compose: $F('composeCache'),
+ imp_compose: document.getElementById('composeCache').value,
type: type,
view: this.mbox
}, {
@@ -65,8 +65,9 @@ var ImpMessage = {
updateAddressHeader: function(e)
{
+ var tr = e.target.closest('TR');
ImpCore.doAction('addressHeader', {
- header: e.element().up('TR').identify().substring(9).toLowerCase(),
+ header: tr.id.substring(9).toLowerCase(),
view: this.mbox
}, {
callback: this._updateAddressHeaderCallback.bind(this),
@@ -76,19 +77,20 @@ var ImpMessage = {
_updateAddressHeaderCallback: function(r)
{
- $H(r.hdr_data).each(function(d) {
- this.updateHeader(d.key, d.value);
+ Object.entries(r.hdr_data).forEach(function(d) {
+ this.updateHeader(d[0], d[1]);
}, this);
},
updateHeader: function(hdr, data, limit)
{
- var elt = $('msgHeader' + hdr.capitalize());
+ var elt = document.getElementById('msgHeader' + hdr.charAt(0).toUpperCase() + hdr.slice(1));
if (elt) {
- elt = elt.show().down('TD:last');
- ImpCore.buildAddressLinks(data, elt, limit);
+ elt.hidden = false;
+ var td = elt.querySelector('TD:last-child');
+ ImpCore.buildAddressLinks(data, td, limit);
if (hdr === 'from' && this.resent) {
- ImpCore.buildResentHeader(elt, this.resent);
+ ImpCore.buildResentHeader(td, this.resent);
delete this.resent;
}
}
@@ -96,14 +98,14 @@ var ImpMessage = {
reloadPart: function(mimeid, params)
{
- ImpCore.doAction('inlineMessageOutput', Object.extend(params, {
+ ImpCore.doAction('inlineMessageOutput', Object.assign(params, {
mimeid: mimeid,
view: this.mbox
}), {
callback: function(r) {
- $('messageBody')
- .down('DIV[impcontentsmimeid="' + r.mimeid + '"]')
- .replace(r.text);
+ var target = document.getElementById('messageBody')
+ .querySelector('DIV[impcontentsmimeid="' + r.mimeid + '"]');
+ target.outerHTML = r.text;
},
uids: [ this.buid ]
});
@@ -112,22 +114,23 @@ var ImpMessage = {
/* Click handlers. */
clickHandler: function(e)
{
- var base, cnames;
+ var base, cnames,
+ id = e.target.id || (e.target.closest('[id]') || {}).id;
- switch (e.element().readAttribute('id')) {
+ switch (id) {
case 'windowclose':
window.close();
- e.memo.hordecore_stop = true;
+ e.detail.hordecore_stop = true;
break;
case 'forward_link':
this.quickreply('forward_auto');
- e.memo.stop();
+ e.detail.stop();
break;
case 'reply_link':
this.quickreply('reply_auto');
- e.memo.stop();
+ e.detail.stop();
break;
case 'button_delete':
@@ -135,19 +138,19 @@ var ImpMessage = {
case 'button_spam':
if ((base = ImpCore.baseAvailable())) {
base.focus();
- if (e.element().identify() == 'button_delete') {
+ if (id == 'button_delete') {
base.ImpBase.deleteMsg({
mailbox: this.mbox,
uid: this.buid
});
} else {
- base.ImpBase.reportSpam(e.element().identify() == 'button_spam', {
+ base.ImpBase.reportSpam(id == 'button_spam', {
mailbox: this.mbox,
uid: this.buid
});
}
} else {
- if (e.element().identify() == 'button_delete') {
+ if (id == 'button_delete') {
ImpCore.doAction('deleteMessages', {
view: this.mbox
}, {
@@ -156,7 +159,7 @@ var ImpMessage = {
});
} else {
ImpCore.doAction('reportSpam', {
- spam: ~~(e.element().identify() == 'button_spam'),
+ spam: ~~(id == 'button_spam'),
view: this.mbox
}, {
uids: [ this.buid ],
@@ -165,7 +168,7 @@ var ImpMessage = {
}
}
window.close();
- e.memo.hordecore_stop = true;
+ e.detail.hordecore_stop = true;
break;
case 'msg_view_source':
@@ -189,7 +192,7 @@ var ImpMessage = {
break;
case 'qreply':
- if (e.memo.element().match('DIV.headercloseimg IMG')) {
+ if (e.detail.element().match('DIV.headercloseimg IMG')) {
ImpCompose.confirmCancel();
}
break;
@@ -199,37 +202,40 @@ var ImpMessage = {
view: this.mbox
}, {
callback: function(r) {
- $('sendMdnMessage').up(1).fade({ duration: 0.2 });
+ var msg = document.getElementById('sendMdnMessage');
+ if (msg) {
+ msg.parentElement.hidden = true;
+ }
},
uids: [ this.buid ]
});
- e.memo.stop();
+ e.detail.stop();
break;
default:
- cnames = $w(e.element().className);
+ cnames = (e.target.className || '').split(/\s+/);
if (cnames.indexOf('printAtc') !== -1) {
HordeCore.popupWindow(ImpCore.conf.URI_VIEW, {
actionID: 'print_attach',
buid: this.buid,
- id: e.element().readAttribute('mimeid'),
+ id: e.target.getAttribute('mimeid'),
mailbox: this.mbox
}, {
name: this.buid + '|' + this.mbox + '|print',
onload: IMP_JS.printWindow
});
- e.memo.stop();
+ e.detail.stop();
} else if (cnames.indexOf('stripAtc') !== -1) {
if (window.confirm(ImpCore.text.strip_warn)) {
ImpCore.reloadMessage({
actionID: 'strip_attachment',
buid: this.buid,
- id: e.element().readAttribute('mimeid'),
+ id: e.target.getAttribute('mimeid'),
mailbox: this.mbox
});
}
- e.memo.stop();
+ e.detail.stop();
}
break;
}
@@ -237,7 +243,7 @@ var ImpMessage = {
contextOnClick: function(e)
{
- var id = e.memo.elt.readAttribute('id');
+ var id = e.detail.elt.id;
switch (id) {
case 'ctx_reply_reply':
@@ -258,24 +264,25 @@ var ImpMessage = {
resizeWindow: function()
{
- var mb = $('msgData').down('DIV.messageBody');
-
- mb.setStyle({
- height: Math.max(
- document.viewport.getHeight() -
- mb.cumulativeOffset()[1] -
- parseInt(mb.getStyle('paddingTop'), 10) -
- parseInt(mb.getStyle('paddingBottom'), 10),
+ var mb = document.getElementById('msgData').querySelector('DIV.messageBody');
+
+ mb.style.height = Math.max(
+ document.documentElement.clientHeight -
+ mb.getBoundingClientRect().top -
+ parseInt(window.getComputedStyle(mb).paddingTop, 10) -
+ parseInt(window.getComputedStyle(mb).paddingBottom, 10),
0
- ) + 'px'
- });
+ ) + 'px';
},
_mimeTreeCallback: function(r)
{
- $('msg_all_parts').up().hide();
+ var allParts = document.getElementById('msg_all_parts');
+ if (allParts) { allParts.parentElement.hidden = true; }
- $('partlist').show().update(r.tree);
+ var partlist = document.getElementById('partlist');
+ partlist.hidden = false;
+ partlist.innerHTML = r.tree;
this.resizeWindow();
},
@@ -287,7 +294,13 @@ var ImpMessage = {
HordeCore.initHandler('click');
if (ImpCore.conf.disable_compose) {
- $('reply_link', 'forward_link').compact().invoke('up', 'SPAN').invoke('remove');
+ ['reply_link', 'forward_link'].forEach(function(id) {
+ var elt = document.getElementById(id);
+ if (elt) {
+ var span = elt.closest('SPAN');
+ if (span) { span.remove(); }
+ }
+ });
delete ImpCore.context.ctx_contacts['new'];
} else {
ImpCore.addPopdown('reply_link', 'reply');
@@ -298,7 +311,7 @@ var ImpMessage = {
}
/* Set up address linking. */
- [ 'from', 'to', 'cc', 'bcc' ].each(function(a) {
+ [ 'from', 'to', 'cc', 'bcc' ].forEach(function(a) {
if (this[a]) {
this.updateHeader(a, this[a], true);
delete this[a];
@@ -310,7 +323,7 @@ var ImpMessage = {
base.ImpBase.poll();
} else if (this.tasks) {
if (this.tasks['imp:maillog']) {
- this.tasks['imp:maillog'].each(function(l) {
+ this.tasks['imp:maillog'].forEach(function(l) {
if (this.mbox == l.mbox &&
this.buid == l.buid) {
ImpCore.updateMsgLog(l.log);
@@ -328,8 +341,8 @@ var ImpMessage = {
ImpCore.updateAtcList(this.msg_atc);
delete this.msg_atc;
- $('impLoading').hide();
- $('msgData').show();
+ document.getElementById('impLoading').hidden = true;
+ document.getElementById('msgData').hidden = false;
this.resizeWindow();
}
@@ -338,29 +351,17 @@ var ImpMessage = {
/* Attach event handlers. */
/* Initialize onload handler. */
-document.observe('dom:loaded', function() {
- if (Prototype.Browser.IE && !document.addEventListener) {
- // IE 8
- IMP_JS.iframeResize = IMP_JS.iframeResize.wrap(function(parentfunc, e, id) {
- if ($('msgData').visible()) {
- (function() { parentfunc(e, id); }).defer();
- } else {
- IMP_JS.iframeResize.bind(IMP_JS, e, id).defer();
- }
- });
- ImpMessage.onDomLoad.bind(ImpMessage).delay(0.1);
- } else {
- ImpMessage.onDomLoad();
- }
+document.addEventListener('DOMContentLoaded', function() {
+ ImpMessage.onDomLoad();
});
-document.observe('HordeCore:click', ImpMessage.clickHandler.bindAsEventListener(ImpMessage));
-Event.observe(window, 'resize', ImpMessage.resizeWindow.bind(ImpMessage));
+document.addEventListener('HordeCore:click', ImpMessage.clickHandler.bind(ImpMessage));
+window.addEventListener('resize', ImpMessage.resizeWindow.bind(ImpMessage));
/* ContextSensitive events. */
-document.observe('ContextSensitive:click', ImpMessage.contextOnClick.bindAsEventListener(ImpMessage));
+document.addEventListener('ContextSensitive:click', ImpMessage.contextOnClick.bind(ImpMessage));
/* ImpCore handlers. */
-document.observe('ImpCore:updateAddressHeader', ImpMessage.updateAddressHeader.bindAsEventListener(ImpMessage));
+document.addEventListener('ImpCore:updateAddressHeader', ImpMessage.updateAddressHeader.bind(ImpMessage));
/* Define reloadMessage() method for this page. */
ImpCore.reloadMessage = function(params) {
diff --git a/js/passphrase.js b/js/passphrase.js
index e6604bdf7..5c7ce5c70 100644
--- a/js/passphrase.js
+++ b/js/passphrase.js
@@ -10,7 +10,7 @@ var ImpPassphraseDialog = {
display: function(data)
{
- HordeDialog.display(Object.extend(data, {
+ HordeDialog.display(Object.assign(data, {
form_id: 'imp_passphrase',
password: true
}));
@@ -18,11 +18,11 @@ var ImpPassphraseDialog = {
onClick: function(e)
{
- switch (e.element().identify()) {
+ switch (e.target.id || (e.target.closest('[id]') || {}).id) {
case 'imp_passphrase':
HordeCore.doAction(
'checkPassphrase',
- e.findElement('FORM').serialize(true),
+ Object.fromEntries(new FormData(e.target.closest('FORM'))),
{ callback: this.callback.bind(this) }
);
break;
@@ -39,4 +39,4 @@ var ImpPassphraseDialog = {
};
-document.observe('HordeDialog:onClick', ImpPassphraseDialog.onClick.bindAsEventListener(ImpPassphraseDialog));
+document.addEventListener('HordeDialog:onClick', ImpPassphraseDialog.onClick.bind(ImpPassphraseDialog));
diff --git a/js/prefs/acl.js b/js/prefs/acl.js
index 36cc77e15..862c24793 100644
--- a/js/prefs/acl.js
+++ b/js/prefs/acl.js
@@ -6,21 +6,29 @@
* @license GPL-2 (http://www.horde.org/licenses/gpl)
*/
-document.observe('dom:loaded', function() {
- $('aclmbox').observe('change', function(e) {
- $($('prefs').getInputs('checkbox')).flatten().invoke('disable');
- $('change_acl_mbox').setValue(1);
- $('prefs').submit();
+document.addEventListener('DOMContentLoaded', function() {
+ document.getElementById('aclmbox').addEventListener('change', function() {
+ document.getElementById('prefs').querySelectorAll('input[type="checkbox"]').forEach(function(i) {
+ i.disabled = true;
+ });
+ document.getElementById('change_acl_mbox').value = 1;
+ document.getElementById('prefs').submit();
});
/* Disable selection of container elements. */
- $('aclmbox').select('OPTION[value=""]').invoke('writeAttribute', 'disabled', true);
+ document.getElementById('aclmbox').querySelectorAll('option[value=""]').forEach(function(o) {
+ o.disabled = true;
+ });
- $$('TABLE.prefsAclTable')[0].on('change', 'SELECT.aclTemplate', function(e, elt) {
- var acl = $F(elt);
+ document.querySelector('table.prefsAclTable').addEventListener('change', function(e) {
+ var elt = e.target;
+ if (!elt.matches('select.aclTemplate')) {
+ return;
+ }
- elt.up('TR').select('INPUT[type=checkbox]').each(function(i) {
- i.setValue(acl.include(i.value));
+ var acl = elt.value;
+ elt.closest('tr').querySelectorAll('input[type=checkbox]').forEach(function(i) {
+ i.checked = acl.includes(i.value);
});
elt.selectedIndex = 0;
diff --git a/js/prefs/flag.js b/js/prefs/flag.js
index 311f2bd34..0d6a947be 100644
--- a/js/prefs/flag.js
+++ b/js/prefs/flag.js
@@ -20,32 +20,32 @@ var ImpFlagPrefs = {
_sendData: function(a, d)
{
- $('flag_action').setValue(a);
- $('flag_data').setValue(d);
- $('prefs').submit();
+ document.getElementById('flag_action').value = a;
+ document.getElementById('flag_data').value = d;
+ document.getElementById('prefs').submit();
},
changeHandler: function(e, elt)
{
- if (elt.identify().startsWith('bg_')) {
- elt.setStyle({ background: elt.getValue() });
+ if (elt.id.startsWith('bg_')) {
+ elt.style.background = elt.value;
}
},
clickHandler: function(e)
{
var cnames, elt2,
- elt = e.element();
+ elt = e.detail.element();
- if (elt.readAttribute('id') == 'new_button') {
+ if (elt.id == 'new_button') {
this.addFlag();
} else {
- cnames = $w(elt.className);
+ cnames = elt.className.split(/\s+/);
if (cnames.indexOf('flagcolorpicker') !== -1) {
- elt2 = elt.previous('INPUT');
+ elt2 = elt.previousElementSibling;
new ColorPicker({
- color: $F(elt2),
+ color: elt2.value,
draggable: true,
offsetParent: elt,
resizable: true,
@@ -54,21 +54,21 @@ var ImpFlagPrefs = {
[ elt2, 'background' ]
]
});
- e.memo.stop();
+ e.detail.stop();
} else if (cnames.indexOf('flagdelete') !== -1) {
if (window.confirm(this.confirm_delete)) {
- this._sendData('delete', elt.previous('INPUT').readAttribute('id'));
+ this._sendData('delete', elt.previousElementSibling.id);
}
- e.memo.stop();
+ e.detail.stop();
}
}
},
resetHandler: function()
{
- $('prefs').getInputs('text').each(function(i) {
- if (i.readAttribute('id').startsWith('color_')) {
- i.setStyle({ backgroundColor: $F(i) });
+ document.getElementById('prefs').querySelectorAll('input[type="text"]').forEach(function(i) {
+ if (i.id.startsWith('color_')) {
+ i.style.backgroundColor = i.value;
}
});
},
@@ -76,13 +76,17 @@ var ImpFlagPrefs = {
onDomLoad: function()
{
HordeCore.initHandler('click');
- $('prefs').observe('reset', function() {
- this.resetHandler.delay(0.1);
+ document.getElementById('prefs').addEventListener('reset', function() {
+ setTimeout(this.resetHandler.bind(this), 100);
}.bind(this));
}
};
-document.observe('dom:loaded', ImpFlagPrefs.onDomLoad.bind(ImpFlagPrefs));
-document.observe('HordeCore:click', ImpFlagPrefs.clickHandler.bindAsEventListener(ImpFlagPrefs));
-document.on('change', 'INPUT', ImpFlagPrefs.changeHandler.bind(ImpFlagPrefs));
+document.addEventListener('DOMContentLoaded', ImpFlagPrefs.onDomLoad.bind(ImpFlagPrefs));
+document.addEventListener('HordeCore:click', ImpFlagPrefs.clickHandler.bind(ImpFlagPrefs));
+document.addEventListener('change', function(e) {
+ if (e.target.matches('INPUT')) {
+ ImpFlagPrefs.changeHandler(e, e.target);
+ }
+});
diff --git a/js/prefs/pgp.js b/js/prefs/pgp.js
index 409557a00..175358ff7 100644
--- a/js/prefs/pgp.js
+++ b/js/prefs/pgp.js
@@ -10,22 +10,25 @@ var ImpPgp = {
replaceDate: function(d)
{
- $('generate_expire_date').setValue(d.getTime()).next('SPAN').update(this.months[d.getMonth()] + ' ' + d.getDate() + ', ' + (d.getFullYear()));
+ var elt = document.getElementById('generate_expire_date');
+ elt.value = d.getTime();
+ elt.nextElementSibling.textContent = this.months[d.getMonth()] + ' ' + d.getDate() + ', ' + d.getFullYear();
},
clickHandler: function(e)
{
- var elt = e.element();
+ var elt = e.detail.element();
- switch (elt.readAttribute('id')) {
+ switch (elt.id) {
case 'generate_expire':
- elt.next().toggle();
+ var sib = elt.nextElementSibling;
+ sib.hidden = !sib.hidden;
break;
default:
- if (elt.hasClassName('calendarImg')) {
- Horde_Calendar.open(elt.identify(), new Date(Number($('generate_expire_date').getValue())));
- e.memo.stop();
+ if (elt.classList.contains('calendarImg')) {
+ Horde_Calendar.open(elt.id, new Date(Number(document.getElementById('generate_expire_date').value)));
+ e.detail.stop();
}
break;
}
@@ -33,7 +36,7 @@ var ImpPgp = {
calendarSelectHandler: function(e)
{
- this.replaceDate(e.memo);
+ this.replaceDate(e.detail);
},
onDomLoad: function()
@@ -47,6 +50,6 @@ var ImpPgp = {
};
-document.observe('dom:loaded', ImpPgp.onDomLoad.bind(ImpPgp));
-document.observe('HordeCore:click', ImpPgp.clickHandler.bindAsEventListener(ImpPgp));
-document.observe('Horde_Calendar:select', ImpPgp.calendarSelectHandler.bindAsEventListener(ImpPgp));
+document.addEventListener('DOMContentLoaded', ImpPgp.onDomLoad.bind(ImpPgp));
+document.addEventListener('HordeCore:click', ImpPgp.clickHandler.bind(ImpPgp));
+document.addEventListener('Horde_Calendar:select', ImpPgp.calendarSelectHandler.bind(ImpPgp));
diff --git a/js/prefs/remote.js b/js/prefs/remote.js
index 8f363d6e4..c11c6530b 100644
--- a/js/prefs/remote.js
+++ b/js/prefs/remote.js
@@ -13,91 +13,95 @@ var ImpRemotePrefs = {
_sendData: function(a, d, c)
{
- $('remote_action').setValue(a);
- $('remote_data').setValue(d);
+ document.getElementById('remote_action').value = a;
+ document.getElementById('remote_data').value = d;
if (c) {
- $('prefs').getInputs('hidden', 'actionID').first().clear();
+ document.querySelector('#prefs input[type="hidden"][name="actionID"]').value = '';
}
- $('prefs').submit();
+ document.getElementById('prefs').submit();
},
_autoconfigCallback: function(r)
{
if (r.success) {
- $('remote_type').setValue(r.mconfig.imap ? 'imap' : 'pop3');
- $('remote_server').setValue(r.mconfig.host);
- $('remote_user').setValue(r.mconfig.username);
- $('remote_port').setValue(r.mconfig.port);
- $('remote_secure_autoconfig').setValue(r.mconfig.tls);
-
- if ($F('remote_label').blank()) {
- $('remote_label').setValue(r.mconfig.label);
+ document.getElementById('remote_type').value = r.mconfig.imap ? 'imap' : 'pop3';
+ document.getElementById('remote_server').value = r.mconfig.host;
+ document.getElementById('remote_user').value = r.mconfig.username;
+ document.getElementById('remote_port').value = r.mconfig.port;
+ document.getElementById('remote_secure_autoconfig').value = r.mconfig.tls;
+
+ if (!document.getElementById('remote_label').value.trim()) {
+ document.getElementById('remote_label').value = r.mconfig.label;
}
- $('remote_password').remove();
- $('autoconfig_button').hide();
- $('add_button').show();
+ document.getElementById('remote_password').remove();
+ document.getElementById('autoconfig_button').hidden = true;
+ document.getElementById('add_button').hidden = false;
} else {
- $('autoconfig_button').setValue(this.next);
+ document.getElementById('autoconfig_button').value = this.next;
}
- $('prefs').enable();
+ Array.from(document.getElementById('prefs').elements).forEach(function(el) {
+ el.disabled = false;
+ });
},
clickHandler: function(e)
{
- if (e.isRightClick()) {
+ if (e.button === 2) {
return;
}
- var elt = e.element();
+ var elt = e.target;
- while (Object.isElement(elt)) {
- if (elt.hasClassName('remotedelete')) {
+ while (elt instanceof Element) {
+ if (elt.classList.contains('remotedelete')) {
if (window.confirm(this.confirm_delete)) {
- this._sendData('delete', elt.readAttribute('data-id'));
+ this._sendData('delete', elt.dataset.id);
}
- e.stop();
+ e.preventDefault();
return;
}
- switch (elt.readAttribute('id')) {
+ switch (elt.id) {
case 'add_button':
this._sendData('add', '');
break;
case 'autoconfig_button':
- if ($F('remote_email').blank()) {
+ if (!document.getElementById('remote_email').value.trim()) {
window.alert(this.empty_email);
- } else if ($F('remote_password').empty()) {
+ } else if (!document.getElementById('remote_password').value) {
window.alert(this.empty_password);
} else {
HordeCore.doAction(
'autoconfigAccount',
{
- email: $F('remote_email'),
- // Base64 encode just to keep password data from
- // being plaintext. A trivial obfuscation, but
- // will prevent passwords from leaking in the
- // event of some sort of data dump.
- password: Base64.encode($F('remote_password')),
+ email: document.getElementById('remote_email').value,
+ password: Base64.encode(document.getElementById('remote_password').value),
password_base64: true,
- secure: ~~($F('remote_secure') == 'yes')
+ secure: ~~(document.getElementById('remote_secure').value == 'yes')
},
{
callback: this._autoconfigCallback.bind(this)
}
);
- elt.setValue(this.wait);
- $('prefs').disable();
+ elt.value = this.wait;
+ Array.from(document.getElementById('prefs').elements).forEach(function(el) {
+ el.disabled = true;
+ });
}
- e.stop();
+ e.preventDefault();
break;
case 'advanced_show':
- $('prefs').select('.imp-remote-autoconfig').invoke('hide');
- $('remote_secure_autoconfig').remove();
- $('prefs').select('.imp-remote-advanced').invoke('show');
+ document.querySelectorAll('#prefs .imp-remote-autoconfig').forEach(function(el) {
+ el.hidden = true;
+ });
+ document.getElementById('remote_secure_autoconfig').remove();
+ document.querySelectorAll('#prefs .imp-remote-advanced').forEach(function(el) {
+ el.hidden = false;
+ });
break;
case 'cancel_button':
@@ -109,10 +113,10 @@ var ImpRemotePrefs = {
break;
}
- elt = elt.up();
+ elt = elt.parentElement;
}
}
};
-document.observe('click', ImpRemotePrefs.clickHandler.bindAsEventListener(ImpRemotePrefs));
+document.addEventListener('click', ImpRemotePrefs.clickHandler.bind(ImpRemotePrefs));
diff --git a/js/prefs/signaturehtml.js b/js/prefs/signaturehtml.js
index 6d0e80139..c521a2089 100644
--- a/js/prefs/signaturehtml.js
+++ b/js/prefs/signaturehtml.js
@@ -12,12 +12,12 @@ var ImpHtmlSignaturePrefs = {
changeIdentity: function(e)
{
- switch (e.memo.pref) {
+ switch (e.detail.pref) {
case 'signature_html_select':
if (this.editor) {
- this.editor.setData(this.sigs[e.memo.i]);
+ this.editor.setData(this.sigs[e.detail.i]);
} else {
- this.changeIdentity.bind(this, e).delay(0.1);
+ setTimeout(this.changeIdentity.bind(this, e), 100);
}
break;
}
@@ -72,5 +72,5 @@ var ImpHtmlSignaturePrefs = {
};
-document.observe('dom:loaded', ImpHtmlSignaturePrefs.onDomLoad.bind(ImpHtmlSignaturePrefs));
-document.observe('HordeIdentitySelect:change', ImpHtmlSignaturePrefs.changeIdentity.bindAsEventListener(ImpHtmlSignaturePrefs));
+document.addEventListener('DOMContentLoaded', ImpHtmlSignaturePrefs.onDomLoad.bind(ImpHtmlSignaturePrefs));
+document.addEventListener('HordeIdentitySelect:change', ImpHtmlSignaturePrefs.changeIdentity.bind(ImpHtmlSignaturePrefs));
diff --git a/js/syntaxhighlighter.js b/js/syntaxhighlighter.js
index c7d1e3915..6afa5ffb3 100644
--- a/js/syntaxhighlighter.js
+++ b/js/syntaxhighlighter.js
@@ -1 +1,4 @@
-$('messageBody') && $('messageBody').observe('IMP_Preview:loadedFromCache', function() { window.SyntaxHighlighter.highlight(); });
+var mb = document.getElementById('messageBody');
+if (mb) {
+ mb.addEventListener('IMP_Preview:loadedFromCache', function() { window.SyntaxHighlighter.highlight(); });
+}
diff --git a/js/viewport.js b/js/viewport.js
index 4303e385c..66ba06282 100644
--- a/js/viewport.js
+++ b/js/viewport.js
@@ -1396,18 +1396,18 @@ ViewPort_Scroller = Class.create({
this.scrollDiv = new Element('DIV', { className: 'vpScroll' }).setStyle({ cssFloat: 'right', overflow: 'hidden' }).hide();
c.insert({ before: this.scrollDiv });
- this.scrollDiv.observe('Slider2:change', function() {
+ this.scrollDiv.addEventListener('Slider2:change', function() {
if (!this.noupdate) {
this.vp.requestContentRefresh(this.currentOffset());
}
}.bind(this));
- this.scrollDiv.observe('Slider2:end', function() {
+ this.scrollDiv.addEventListener('Slider2:end', function() {
this.vp.opts.container.fire('ViewPort:sliderEnd');
}.bind(this));
- this.scrollDiv.observe('Slider2:slide', function() {
+ this.scrollDiv.addEventListener('Slider2:slide', function() {
this.vp.opts.container.fire('ViewPort:sliderSlide');
}.bind(this));
- this.scrollDiv.observe('Slider2:start', function() {
+ this.scrollDiv.addEventListener('Slider2:start', function() {
this.vp.opts.container.fire('ViewPort:sliderStart');
}.bind(this));
diff --git a/js/viewport_utils.js b/js/viewport_utils.js
index 4917971ee..b3786967d 100644
--- a/js/viewport_utils.js
+++ b/js/viewport_utils.js
@@ -6,20 +6,20 @@
* @license GPL-2 (http://www.horde.org/licenses/gpl)
*/
-Object.extend(Array.prototype, {
+Object.assign(Array.prototype, {
// Need our own diff() function because prototypejs's without() function
// does not handle array input.
diff: function(values)
{
- return this.select(function(value) {
- return !values.include(value);
+ return this.filter(function(value) {
+ return values.indexOf(value) === -1;
});
},
numericSort: function()
{
- return this.collect(Number).sort(function(a, b) {
+ return this.map(Number).sort(function(a, b) {
return (a > b) ? 1 : ((a < b) ? -1 : 0);
});
},
@@ -30,12 +30,12 @@ Object.extend(Array.prototype, {
{
opts = opts || {};
- var u = (opts.raw ? this.clone() : this.numericSort()),
+ var u = (opts.raw ? this.slice() : this.numericSort()),
first = u.shift(),
last = first,
out = [];
- u.each(function(k) {
+ u.forEach(function(k) {
if (!opts.raw && (last + 1 == k)) {
last = k;
} else {
@@ -50,18 +50,21 @@ Object.extend(Array.prototype, {
});
-Object.extend(String.prototype, {
+Object.assign(String.prototype, {
parseViewportUidString: function()
{
var out = [];
- this.strip().split(',').each(function(e) {
+ this.trim().split(',').forEach(function(e) {
var r = e.split(':');
- if (r.size() == 1) {
+ if (r.length == 1) {
out.push(Number(e));
} else {
- out = out.concat($A($R(Number(r[0]), Number(r[1]))));
+ var start = Number(r[0]), end = Number(r[1]);
+ for (var i = start; i <= end; i++) {
+ out.push(i);
+ }
}
});
diff --git a/lib/Ajax/Application.php b/lib/Ajax/Application.php
index 1707d350e..1bef72e6d 100644
--- a/lib/Ajax/Application.php
+++ b/lib/Ajax/Application.php
@@ -12,6 +12,9 @@
* @package IMP
*/
+use Horde\Imp\AppAuthMode;
+use Horde\Imp\Ajax\FederatedUnsupportedException;
+
/**
* Defines the AJAX interface for IMP.
*
@@ -47,12 +50,26 @@ class IMP_Ajax_Application extends Horde_Core_Ajax_Application
*/
public $queue;
+ /**
+ * True if IMP is running with app_auth_mode = 'federated' (mailbox
+ * accounts are not split into a privileged "main" account plus
+ * "remote" accounts and every account is equal. IMP does not perform
+ * its own application-level authentication). False (the default) is
+ * the classic/traditional model.
+ *
+ * @see \Horde\Imp\AppAuthMode
+ * @var boolean
+ */
+ public $federated = false;
+
/**
*/
protected function _init()
{
global $injector, $registry;
+ $this->federated = $injector->get(AppAuthMode::class)->isFederated();
+
$this->queue = $injector->getInstance('IMP_Ajax_Queue');
switch ($registry->getView()) {
@@ -66,7 +83,8 @@ protected function _init()
$this->addHandler('IMP_Ajax_Application_Handler_Mboxtoggle');
$this->addHandler('IMP_Ajax_Application_Handler_Passphrase');
$this->addHandler('IMP_Ajax_Application_Handler_Search');
- if ($injector->getInstance('IMP_Factory_Imap')->create()->access(IMP_Imap::ACCESS_REMOTE)) {
+ if (!$this->federated
+ && $injector->getInstance('IMP_Factory_Imap')->create()->access(IMP_Imap::ACCESS_REMOTE)) {
$this->addHandler('IMP_Ajax_Application_Handler_Remote');
$this->addHandler('IMP_Ajax_Application_Handler_RemotePrefs');
}
@@ -116,15 +134,26 @@ protected function _init()
);
}
- /* Check for global poll task. */
+ /* Check for global poll task.
+ *
+ * Federated mode: An empty poll list traditionally means "poll
+ * all mailboxes tracked by IMP_Ftree" which doesn't exist here.
+ * Only honor an explicit mailbox list. Skip the whole-tree poll
+ * until a federated-aware poll list exists. */
if (isset($this->_vars->poll)) {
$poll = json_decode($this->_vars->poll);
- $this->queue->poll(
- empty($poll)
- ? $injector->getInstance('IMP_Ftree')->poll->getPollList()
- : IMP_Mailbox::formFrom($poll),
- true
- );
+ if ($this->federated) {
+ if (!empty($poll)) {
+ $this->queue->poll(IMP_Mailbox::formFrom($poll), true);
+ }
+ } else {
+ $this->queue->poll(
+ empty($poll)
+ ? $injector->getInstance('IMP_Ftree')->poll->getPollList()
+ : IMP_Mailbox::formFrom($poll),
+ true
+ );
+ }
}
}
@@ -156,6 +185,28 @@ public function getTasks()
/* Shared code between handlers. */
+ /**
+ * Guard an AJAX action that has no federated-mode implementation yet.
+ *
+ * Handlers whose backend behavior still depends on the legacy base
+ * IMP_Imap (acquired via IMP_Factory_Imap::create()) call this at the top
+ * of their federated path. In traditional mode it is a no-op. In federated
+ * mode it throws a typed, correctly-attributed error instead of letting the
+ * request fall through to legacy IMAP code, where IMP_Imap::__call() would
+ * raise a Horde_Exception_AuthenticationFailure that the client renders as
+ * a misleading session timeout.
+ *
+ * @param string $action The AJAX action name, for the error message.
+ *
+ * @throws FederatedUnsupportedException If running federated.
+ */
+ public function assertFederatedSupported($action)
+ {
+ if ($this->federated) {
+ throw new FederatedUnsupportedException($action);
+ }
+ }
+
/**
* Initialize the objects needed to compose.
*
diff --git a/lib/Ajax/Application/Handler/Dynamic.php b/lib/Ajax/Application/Handler/Dynamic.php
index d4d49a553..635eb23c0 100644
--- a/lib/Ajax/Application/Handler/Dynamic.php
+++ b/lib/Ajax/Application/Handler/Dynamic.php
@@ -69,7 +69,6 @@ public function createMailboxPrepare()
public function createMailbox()
{
global $injector, $notification;
-
if (!isset($this->vars->mbox)) {
return false;
}
@@ -291,21 +290,17 @@ public function flagAll()
public function listMailboxes()
{
global $injector, $prefs, $session;
-
$ftree = $injector->getInstance('IMP_Ftree');
$iterator = new AppendIterator();
-
/* This might be a long running operation. */
if ($this->vars->initial) {
$session->close();
$ftree->eltdiff->clear();
-
/* @todo: Correctly handle unsubscribed mailboxes in ftree. */
if ($ftree->unsubscribed_loaded && !$this->vars->reload) {
$ftree->init();
}
}
-
if ($this->vars->reload) {
$ftree->init();
}
@@ -416,7 +411,6 @@ public function listMailboxes()
$ftree->expand($val);
}
}
-
array_map(
[$ftree->eltdiff, 'add'],
array_unique(iterator_to_array($iterator, false))
@@ -433,7 +427,6 @@ public function listMailboxes()
$this->vars->reload = false;
}
}
-
return true;
}
@@ -447,17 +440,69 @@ public function listMailboxes()
*/
public function dynamicInit()
{
- $this->_base->callAction('viewPort');
-
- $this->vars->initial = 1;
- $this->vars->mboxes = json_encode([$this->vars->mailbox]);
- $this->listMailboxes();
-
+ if ($this->_base->federated) {
+ /* Federated mode: there is no privileged "main account" mailbox
+ * and no IMP_Ftree-based folder tree to iterate. The classic
+ * viewPort/listMailboxes calls both assume a backend-connected
+ * base account (IMP_Factory_Imap::create() with IMP_Imap->init),
+ * which does not exist here.
+ *
+ * Until federated account resolution feeds these tasks, queue the
+ * minimum empty payloads the dynamic-view JS client expects so its
+ * initial bootstrap completes cleanly:
+ *
+ * - 'viewport': empty message list. Replaced once a mailbox is
+ * resolved from a federated account and can drive
+ * IMP_Ajax_Application_ListMessages.
+ * - 'mailbox': empty folder-tree delta (base.js mailboxCallback
+ * reads no added/changed/deleted nodes). Replaced once folders
+ * are enumerated over a federated connection.
+ *
+ * The 'flag-config' task below is emitted for both modes; in
+ * federated mode IMP_Ajax_Queue currently flushes it as an empty
+ * list, which base.js flagConfigCallback treats as a no-op. */
+ $this->_base->addTask('viewport', $this->_federatedViewportStub());
+ $this->_base->addTask('mailbox', new stdClass());
+ } else {
+ $this->_base->callAction('viewPort');
+ $this->vars->initial = 1;
+ // In FW 6.1 imp, the mailbox property may be unset and mboxes might be empty
+ $this->vars->mboxes = json_encode([$this->vars?->mailbox]);
+ $this->listMailboxes();
+ }
$this->_base->queue->flagConfig(Horde_Registry::VIEW_DYNAMIC);
-
return true;
}
+ /**
+ * Build the minimum "viewport" task payload expected by the
+ * dynamic-view JS ViewPort class when running in federated mode,
+ * where no mailbox/account has been resolved yet.
+ *
+ * Deliberately does not touch IMP_Mailbox/IMP_Ftree/IMP_Imap: Unlike
+ * IMP_Ajax_Application_Viewport which derives 'cacheid' from a real,
+ * backend-connected mailbox this stub must remain safe to build with
+ * zero configured mail accounts.
+ *
+ * @return object An object exposing toObject(), as expected by
+ * IMP_Ajax_Application::getTasks() for the
+ * 'imp:viewport' task.
+ */
+ protected function _federatedViewportStub()
+ {
+ return new class {
+ public function toObject()
+ {
+ $ob = new stdClass();
+ $ob->view = '';
+ $ob->cacheid = strval(new Horde_Support_Randomid());
+ $ob->data = new stdClass();
+ $ob->rowlist = new stdClass();
+ return $ob;
+ }
+ };
+ }
+
/**
* AJAX action: Modify list of polled mailboxes.
*
diff --git a/lib/Ajax/Queue.php b/lib/Ajax/Queue.php
index f54b787b9..d08af1dcd 100644
--- a/lib/Ajax/Queue.php
+++ b/lib/Ajax/Queue.php
@@ -218,41 +218,67 @@ public function add(IMP_Ajax_Application $ajax)
$this->_flag = [];
}
- /* Add flag configuration. */
- switch ($this->_flagconfig) {
- case Horde_Registry::VIEW_DYNAMIC:
- case Horde_Registry::VIEW_MINIMAL:
- case Horde_Registry::VIEW_SMARTMOBILE:
- $flags = [];
- foreach ($injector->getInstance('IMP_Flags')->getList() as $val) {
- $tmp = [
- 'b' => $val->bgdefault ? null : $val->bgcolor,
- 'f' => $val->fgcolor,
- 'id' => $val->id,
- 'l' => $val->label,
- 's' => intval($val instanceof IMP_Flag_Imap),
- ];
-
- if ($this->_flagconfig === Horde_Registry::VIEW_DYNAMIC) {
- $tmp += [
- 'a' => $val->canset,
- 'c' => $val->css,
- 'i' => $val->css ? null : $val->cssicon,
- 'u' => intval($val instanceof IMP_Flag_User),
+ /* Add flag configuration.
+ *
+ * Federated mode check: Until a federated-aware
+ * flag source exists, emit an empty flag config
+ * list which the JS client (base.js tasksHandler()) treats as a
+ * no-op update. */
+ if ($ajax->federated) {
+ switch ($this->_flagconfig) {
+ case Horde_Registry::VIEW_DYNAMIC:
+ case Horde_Registry::VIEW_MINIMAL:
+ case Horde_Registry::VIEW_SMARTMOBILE:
+ $ajax->addTask('flag-config', []);
+ break;
+ }
+ } else {
+ switch ($this->_flagconfig) {
+ case Horde_Registry::VIEW_DYNAMIC:
+ case Horde_Registry::VIEW_MINIMAL:
+ case Horde_Registry::VIEW_SMARTMOBILE:
+ $flags = [];
+ foreach ($injector->getInstance('IMP_Flags')->getList() as $val) {
+ $tmp = [
+ 'b' => $val->bgdefault ? null : $val->bgcolor,
+ 'f' => $val->fgcolor,
+ 'id' => $val->id,
+ 'l' => $val->label,
+ 's' => intval($val instanceof IMP_Flag_Imap),
];
- }
- $flags[] = array_filter($tmp);
- }
- $ajax->addTask('flag-config', $flags);
- break;
+ if ($this->_flagconfig === Horde_Registry::VIEW_DYNAMIC) {
+ $tmp += [
+ 'a' => $val->canset,
+ 'c' => $val->css,
+ 'i' => $val->css ? null : $val->cssicon,
+ 'u' => intval($val instanceof IMP_Flag_User),
+ ];
+ }
+
+ $flags[] = array_filter($tmp);
+ }
+ $ajax->addTask('flag-config', $flags);
+ break;
+ }
}
- /* Add folder tree information. */
- $this->_addFtreeInfo($ajax);
+ /* Add folder tree information.
+ *
+ * IMP_Ftree models the traditional main-account/remote-account
+ * tree which does not exist in federated mode.
+ */
+ if (!$ajax->federated) {
+ $this->_addFtreeInfo($ajax);
+ }
- /* Add maillog information. */
- $this->_addMaillogInfo($ajax);
+ /* Add maillog information.
+ *
+ * _addMaillogInfo() resolves messages via IMP_Indices
+ */
+ if (!$ajax->federated) {
+ $this->_addMaillogInfo($ajax);
+ }
/* Add message information. */
if (!empty($this->_messages)) {
@@ -260,34 +286,50 @@ public function add(IMP_Ajax_Application $ajax)
$this->_messages = [];
}
- /* Add poll information. */
- $poll = $poll_list = [];
- if (!empty($this->_poll)) {
- foreach ($this->_poll as $val) {
- $poll_list[strval($val)] = 1;
+ /* Add poll information.
+ *
+ * Federated mode skips the unseen-count lookup for now.
+ */
+ if ($ajax->federated) {
+ $this->_poll = [];
+ } else {
+ $poll = $poll_list = [];
+ if (!empty($this->_poll)) {
+ foreach ($this->_poll as $val) {
+ $poll_list[strval($val)] = 1;
+ }
}
- }
- if (count($poll_list)) {
- $imap_ob = $injector->getInstance('IMP_Factory_Imap')->create();
- if ($imap_ob->init) {
- try {
- foreach ($imap_ob->status(array_keys($poll_list), Horde_Imap_Client::STATUS_UNSEEN) as $key => $val) {
- $poll[IMP_Mailbox::formTo($key)] = intval($val['unseen']);
+ if (count($poll_list)) {
+ $imap_ob = $injector->getInstance('IMP_Factory_Imap')->create();
+ if ($imap_ob->init) {
+ try {
+ foreach ($imap_ob->status(array_keys($poll_list), Horde_Imap_Client::STATUS_UNSEEN) as $key => $val) {
+ $poll[IMP_Mailbox::formTo($key)] = intval($val['unseen']);
+ }
+ } catch (Exception $e) {
+ // Ignore errors in status() calls.
}
- } catch (Exception $e) {
- // Ignore errors in status() calls.
}
- }
- if (!empty($poll)) {
- $ajax->addTask('poll', $poll);
- $this->_poll = [];
+ if (!empty($poll)) {
+ $ajax->addTask('poll', $poll);
+ $this->_poll = [];
+ }
}
}
- /* Add quota information. */
- if ($this->_quota
+ /* Add quota information.
+ *
+ * Federated mode skips quota for now.
+ *
+ * IMP_Quota_Ui::quota() assumes a single
+ * default backend via IMP_Factory_Imap->create(). Skip and clear
+ * any queued quota request until a federated-aware quota source
+ * exists. */
+ if ($ajax->federated) {
+ $this->_quota = false;
+ } elseif ($this->_quota
&& ($quotadata = $injector->getInstance('IMP_Quota_Ui')->quota($this->_quota[0], $this->_quota[1]))) {
$ajax->addTask('quota', [
'm' => $quotadata['message'],
diff --git a/lib/Application.php b/lib/Application.php
index 803387c4b..05d469895 100644
--- a/lib/Application.php
+++ b/lib/Application.php
@@ -31,6 +31,13 @@
* Horde_Registry_Application::). */
require_once HORDE_BASE . '/lib/core.php';
+use Horde\Imp\AppAuthMode;
+use Horde\Imp\Mailbox\MailboxAccountManager;
+use Horde\Imp\Mailbox\MailboxAccountManagerFactory;
+use Horde\Imp\Mailbox\MailboxCredentialSource;
+use Horde\Imp\Mailbox\SessionCredentialSource;
+use Horde\Imp\Mailbox\SiteAccountsProvider;
+use Horde\Imp\Mailbox\SiteAccountsProviderFactory;
use Horde\Util\Variables;
/**
@@ -119,9 +126,41 @@ protected function _bootstrap()
$injector->bindFactory($key, $val, 'create');
}
+ /* In federated mode IMP does not provide application authentication:
+ * Horde identity comes from another mechanism (e.g. OIDC). Stop
+ * advertising IMP as a mailbox auth driver. */
+ $federated = $injector->get(AppAuthMode::class)->isFederated();
+ if ($federated) {
+ $this->auth = array_diff($this->auth, ['authenticate', 'transparent']);
+
+ /* Federated Mode mailbox account layer. The account manager
+ * resolves accounts from configured backends and hands out lazy
+ * per-account connections. The credential source turns the
+ * authenticated Horde session into a per-account mailbox
+ * credential so getConnection() works without explicit
+ * credentials. */
+ $injector->bindFactory(
+ SiteAccountsProvider::class,
+ SiteAccountsProviderFactory::class,
+ 'create'
+ );
+ $injector->bindImplementation(
+ MailboxCredentialSource::class,
+ SessionCredentialSource::class
+ );
+ $injector->bindFactory(
+ MailboxAccountManager::class,
+ MailboxAccountManagerFactory::class,
+ 'create'
+ );
+ }
+
/* Methods only available if admin config is set for this
- * server/login. */
- if (empty($injector->getInstance('IMP_Factory_Imap')->create()->config->admin)) {
+ * server/login. Skipped in federated mode to avoid an eager IMAP
+ * connection on every pushApp('imp'); the admin capabilities are
+ * resolved per-account once an account is opened. */
+ if (!$federated &&
+ empty($injector->getInstance('IMP_Factory_Imap')->create()->config->admin)) {
$this->auth = array_diff($this->auth, ['add', 'list', 'remove']);
}
@@ -134,6 +173,13 @@ protected function _bootstrap()
*/
protected function _authenticated()
{
+ global $injector;
+
+ /* Federated mode does not have a "main" account which implies IMP application level authentication. */
+ if ($injector->get(AppAuthMode::class)->isFederated()) {
+ return;
+ }
+
IMP_Auth::authenticateCallback();
}
diff --git a/lib/Auth.php b/lib/Auth.php
index c066b04d7..c7c807582 100644
--- a/lib/Auth.php
+++ b/lib/Auth.php
@@ -38,12 +38,18 @@ class IMP_Auth
*/
public static function authenticate($credentials = [])
{
- global $injector, $registry;
+ global $conf, $injector, $registry;
- // Do 'horde' authentication.
+ // Do 'horde' authentication. This passthrough also applies in
+ // federated app-auth mode, where Horde identity is established by an
+ // external mechanism and IMP performs no primary-IMAP authentication:
+ // a valid Horde principal is accepted, absence is rejected.
$imp_app = $registry->getApiInstance('imp', 'application');
- if (!empty($imp_app->initParams['authentication'])
- && ($imp_app->initParams['authentication'] == 'horde')) {
+ $federated = !empty($conf['imp']['app_auth_mode'])
+ && ($conf['imp']['app_auth_mode'] == 'federated');
+ if ($federated
+ || (!empty($imp_app->initParams['authentication'])
+ && ($imp_app->initParams['authentication'] == 'horde'))) {
if ($registry->getAuth()) {
return;
}
diff --git a/lib/Ftree.php b/lib/Ftree.php
index 0216bc17d..26a5d973a 100644
--- a/lib/Ftree.php
+++ b/lib/Ftree.php
@@ -104,9 +104,12 @@ class IMP_Ftree implements ArrayAccess, Countable, IteratorAggregate, Serializab
/**
* Constructor.
+ * Archaic: No DI, internal construction of dependencies, reliance on global prefs, injector, session and legacy registry.
+ * TODO: Allow injecting dependencies as optional args first.
*/
public function __construct()
{
+ // FTREE should know if it operates in classic mode (main account + remotes) or modern mode (all accounts are equally "remotes")
$this->init();
}
@@ -149,7 +152,7 @@ public function __get($name)
public function init()
{
global $injector, $session;
-
+ /* TODO: For a truely multi-account setup this logic must be reworked. access_folders must be decided per-account */
$access_folders = $injector->getInstance('IMP_Factory_Imap')->create()->access(IMP_Imap::ACCESS_FOLDERS);
/* Reset class variables to the defaults. */
@@ -171,9 +174,12 @@ public function init()
}
/* Add base account. */
+ /* TODO: Adding "base account" and "Remotes" only makes sense in traditional mailbox handling.
+For federated mailbox handling this may be an empty list and all accounts (if any) are of the same basic type */
$ob = $this->_accounts[self::BASE_ELT] = $access_folders
? new IMP_Ftree_Account_Imap()
: new IMP_Ftree_Account_Inboxonly();
+ // TODO: This should be array_map($this->_insertElt(), $ob->getList) in PHP 8.1+
array_map([$this, '_insertElt'], $ob->getList(null, $mask));
if ($access_folders) {
diff --git a/lib/Mailbox.php b/lib/Mailbox.php
index 77a3a9cae..a4b0c0ec5 100644
--- a/lib/Mailbox.php
+++ b/lib/Mailbox.php
@@ -14,6 +14,7 @@
/**
* This object is a clearinghouse for actions related to an IMP mailbox.
+ * In IMAP lingo, a mailbox is a mail folder inside an account.
*
* @author Michael Slusarz
* @category Horde
diff --git a/lib/Mime/Viewer/Partial.php b/lib/Mime/Viewer/Partial.php
index cd5192c24..3d93aa570 100644
--- a/lib/Mime/Viewer/Partial.php
+++ b/lib/Mime/Viewer/Partial.php
@@ -86,6 +86,13 @@ protected function _getEmbeddedMimeParts()
return null;
}
+ /* RFC 2046 §5.2.2 defines the id parameter as a msg-id. It must
+ * not contain control characters. Reject any such value to
+ * prevent IMAP command injection via a crafted Content-Type header. */
+ if (preg_match('/[\x00-\x1f\x7f]/', $id)) {
+ return null;
+ }
+
/* Perform the search to find the other parts of the message. */
$query = new Horde_Imap_Client_Search_Query();
$query->headerText('Content-Type', $id);
diff --git a/src/Ajax/FederatedUnsupportedException.php b/src/Ajax/FederatedUnsupportedException.php
new file mode 100644
index 000000000..54ece3fcc
--- /dev/null
+++ b/src/Ajax/FederatedUnsupportedException.php
@@ -0,0 +1,67 @@
+
+ * @category Horde
+ * @copyright 2026 Horde LLC
+ * @license http://www.horde.org/licenses/gpl GPL
+ * @package IMP
+ */
+class FederatedUnsupportedException extends IMP_Exception
+{
+ /**
+ * The AJAX action that is not yet supported in federated mode.
+ *
+ * @var string
+ */
+ public string $action;
+
+ /**
+ * Constructor.
+ *
+ * @param string $action The AJAX action name that reached legacy
+ * backend code in federated mode.
+ */
+ public function __construct(string $action)
+ {
+ $this->action = $action;
+
+ parent::__construct(sprintf(
+ 'The "%s" action is not yet available when IMP runs in federated mode.',
+ $action
+ ));
+ }
+}
diff --git a/src/AppAuthMode.php b/src/AppAuthMode.php
new file mode 100644
index 000000000..406376cd7
--- /dev/null
+++ b/src/AppAuthMode.php
@@ -0,0 +1,82 @@
+configLoader
+ ->load('imp')
+ ->get('server.app_auth_mode', 'traditional');
+ }
+
+ /**
+ * Returns true when IMP is operating in federated mode.
+ *
+ * Federated mode: identity comes from an external provider; IMP does
+ * not perform its own application-level authentication.
+ */
+ public function isFederated(): bool
+ {
+ return $this->get() === 'federated';
+ }
+
+ /**
+ * Returns true when IMP is operating in traditional (non-federated) mode.
+ *
+ * Traditional mode: IMP-driven login; primary IMAP connection is opened
+ * eagerly on authentication.
+ */
+ public function isTraditional(): bool
+ {
+ return $this->get() === 'traditional';
+ }
+}
diff --git a/src/ImpBackendConfig.php b/src/ImpBackendConfig.php
new file mode 100644
index 000000000..cf2956375
--- /dev/null
+++ b/src/ImpBackendConfig.php
@@ -0,0 +1,17 @@
+injector->get(BackendConfigLoader::class);
+
+ // IMP uses 'servers' variable in backends.php
+ $state = $loader->load('imp', 'backends.php', 'servers');
+
+ return new ImpBackendConfig($state->toArray());
+ }
+}
diff --git a/src/ImpConfig.php b/src/ImpConfig.php
new file mode 100644
index 000000000..035ad435f
--- /dev/null
+++ b/src/ImpConfig.php
@@ -0,0 +1,21 @@
+get(ImpConfig::class); $somethingDetail = $config->get('something.detail');
+ *
+ * Prefer DI over instantiating $config in your code.
+ */
+
+namespace Horde\Imp;
+
+use Horde\Core\Config\State;
+use Horde\Injector\Attribute\Factory;
+
+#[Factory(factory: ImpConfigFactory::class, method: 'create')]
+class ImpConfig extends State {}
diff --git a/src/ImpConfigFactory.php b/src/ImpConfigFactory.php
new file mode 100644
index 000000000..8331f57c2
--- /dev/null
+++ b/src/ImpConfigFactory.php
@@ -0,0 +1,29 @@
+get(ImpConfig::class); $somethingDetail = $config->get('something.detail');
+ *
+ * Prefer DI over instantiating $config in your code.
+ */
+
+namespace Horde\Imp;
+
+use Horde\Core\Config\ConfigLoader;
+use Horde\Injector\Injector;
+
+class ImpConfigFactory
+{
+ public function __construct(private Injector $injector) {}
+
+ public function create(): ImpConfig
+ {
+ $state = $this->injector->get(ConfigLoader::class)->load('imp');
+ return new ImpConfig($state->toArray());
+ }
+}
diff --git a/src/Mailbox/AccountBoundImapEvent.php b/src/Mailbox/AccountBoundImapEvent.php
new file mode 100755
index 000000000..266d0a135
--- /dev/null
+++ b/src/Mailbox/AccountBoundImapEvent.php
@@ -0,0 +1,60 @@
+innerEvent instanceof AuthenticationSucceeded =>
+ * $this->health->recordSuccess($event->accountId, $event->userId),
+ * $event->innerEvent instanceof AuthenticationFailed =>
+ * $this->health->recordFailure($event->accountId, $event->userId, $event->innerEvent->getMessage()),
+ * default => null,
+ * };
+ * }
+ *
+ * Copyright 2026 The Horde Project (http://www.horde.org/)
+ *
+ * See the enclosed file LICENSE for license information (GPL). If you
+ * did not receive this file, see http://www.horde.org/licenses/gpl.
+ *
+ * @category Horde
+ * @copyright 2026 The Horde Project
+ * @license http://www.horde.org/licenses/gpl GPL
+ * @package IMP
+ */
+final readonly class AccountBoundImapEvent
+{
+ public function __construct(
+ /** Stable account ID from MailboxAccount::getId(). */
+ public string $accountId,
+ /** Horde user ID of the account owner, supplied by the connector at connect time. */
+ public string $userId,
+ /** The original library event. Instanceof-check for specific subtypes. */
+ public ImapEvent $innerEvent,
+ ) {}
+}
diff --git a/src/Mailbox/AccountContextEventDispatcher.php b/src/Mailbox/AccountContextEventDispatcher.php
new file mode 100644
index 000000000..75468bbb6
--- /dev/null
+++ b/src/Mailbox/AccountContextEventDispatcher.php
@@ -0,0 +1,65 @@
+applicationBus->dispatch(
+ new AccountBoundImapEvent($this->accountId, $this->userId, $event)
+ );
+
+ return $event;
+ }
+
+ return $this->applicationBus->dispatch($event);
+ }
+}
diff --git a/src/Mailbox/BackendFilter.php b/src/Mailbox/BackendFilter.php
new file mode 100755
index 000000000..eb60712c1
--- /dev/null
+++ b/src/Mailbox/BackendFilter.php
@@ -0,0 +1,31 @@
+getId());
+ }
+
+ /**
+ * Value equality: same user and same account.
+ */
+ public function equals(ConnectionKey $other): bool
+ {
+ return $this->userId === $other->userId
+ && $this->accountId === $other->accountId;
+ }
+
+ /**
+ * Collision-safe string form for use as an array key.
+ *
+ * The NUL separator cannot occur in a Horde user ID or an account ID, so
+ * distinct (userId, accountId) pairs never collapse to the same string
+ * (unlike a bare concatenation, where "ab" + "c" and "a" + "bc" would).
+ */
+ public function __toString(): string
+ {
+ return $this->userId . "\0" . $this->accountId;
+ }
+}
diff --git a/src/Mailbox/ImapConnection.php b/src/Mailbox/ImapConnection.php
new file mode 100755
index 000000000..763558150
--- /dev/null
+++ b/src/Mailbox/ImapConnection.php
@@ -0,0 +1,38 @@
+getProtocol()) belongs at the construction site once that
+ * class exists.
+ *
+ * Copyright 2026 The Horde Project (http://www.horde.org/)
+ *
+ * See the enclosed file LICENSE for license information (GPL). If you
+ * did not receive this file, see http://www.horde.org/licenses/gpl.
+ *
+ * @category Horde
+ * @copyright 2026 The Horde Project
+ * @license http://www.horde.org/licenses/gpl GPL
+ * @package IMP
+ */
+final class ImpImapConnection implements ImapConnection, LazyMailboxConnection, RecoverableConnection
+{
+ /**
+ * The protocol client built on first getClient(). Null while the
+ * connection is idle.
+ */
+ private ?ImapClient $client = null;
+
+ /**
+ * @param MailboxAccount $account The IMAP account to connect to.
+ * @param MailboxCredential $credential Credential presented at login time.
+ * @param string $userId Horde user ID of the account owner. Carried so
+ * the connection can key itself (see ConnectionKey)
+ * and tag AccountBoundImapEvents with their owner.
+ * @param EventDispatcherInterface|null $dispatcher Optional PSR-14 bus handed to the
+ * ImapClient for connection/auth events.
+ * @param array|null $streamContext Optional PHP stream context passed to the socket
+ * layer, e.g. ['ssl' => ['verify_peer' => false]] to
+ * relax TLS verification. Secure by default (null).
+ * Intended for diagnostics, not request-handling code.
+ */
+ public function __construct(
+ private readonly MailboxAccount $account,
+ private readonly MailboxCredential $credential,
+ private readonly string $userId,
+ private readonly ?EventDispatcherInterface $dispatcher = null,
+ private readonly ?array $streamContext = null,
+ ) {}
+
+ public function getAccount(): MailboxAccount
+ {
+ return $this->account;
+ }
+
+ /**
+ * Horde user ID of the account owner.
+ */
+ public function getUserId(): string
+ {
+ return $this->userId;
+ }
+
+ /**
+ * Composite identity (owner + account) for keying this connection in
+ * connection tables, health maps, and caches.
+ */
+ public function getKey(): ConnectionKey
+ {
+ return ConnectionKey::of($this->userId, $this->account);
+ }
+
+ /**
+ * True once the ImapClient has been built (i.e. getClient() was called at
+ * least once). False means the connection is idle: no client, no stream,
+ * no credential presented.
+ *
+ * This reflects INITIALIZATION, not liveness — a built client may still
+ * hold a dropped socket. Use isAlive() to probe the stream.
+ */
+ public function isInitialized(): bool
+ {
+ return $this->client !== null;
+ }
+
+ /**
+ * The ImapClient for this account, built on first call.
+ *
+ * Building the client opens no socket; the stream is opened lazily on the
+ * first protocol command, and authentication only on an explicit login().
+ * Returns the concrete ImapClient (a covariant narrowing of the
+ * ImapConnection::getClient(): ImapProtocol contract) so callers can reach
+ * login().
+ *
+ * Note: this does NOT verify liveness. Long-running callers should prefer
+ * ensureLive(), which reconnects a dropped stream first.
+ */
+ public function getClient(): ImapClient
+ {
+ if ($this->client === null) {
+ $this->client = $this->buildClient();
+ }
+
+ return $this->client;
+ }
+
+ /**
+ * Probe whether the stream is open and authenticated right now.
+ *
+ * Returns false without side effects when the client was never built. When
+ * a client exists, sends a NOOP and reports success. A NOOP against a
+ * dropped socket surfaces a connection/socket error, which is caught and
+ * reported as not-alive; the dead client is discarded so the next
+ * ensureLive()/reconnect() rebuilds cleanly rather than reusing a client
+ * that ImapClient::noop() may have silently reopened WITHOUT re-login.
+ */
+ public function isAlive(): bool
+ {
+ if ($this->client === null) {
+ return false;
+ }
+
+ try {
+ $this->client->noop();
+
+ return true;
+ } catch (ConnectionException | SocketException) {
+ // The stream is gone. noop() calls connect() internally, so it may
+ // have opened a fresh but UNAUTHENTICATED socket before failing (or
+ // left one open on a partial failure). Drop it so we never hand a
+ // half-open, unauthenticated client back to a caller.
+ $this->client = null;
+
+ return false;
+ }
+ }
+
+ /**
+ * Tear down any existing stream and establish a fresh authenticated one.
+ *
+ * Rebuilds the client from scratch, which re-reads the credential — so a
+ * refreshed OAuth token or a rotated password takes effect here. This is
+ * the single recovery path for both a dropped socket and a rolled-over
+ * credential.
+ */
+ public function reconnect(): void
+ {
+ $this->disconnect();
+ $this->client = $this->buildClient();
+ $this->client->login();
+ }
+
+ /**
+ * Return a client that is guaranteed live and authenticated, reconnecting
+ * if the current stream is dead or was never opened.
+ *
+ * The daemon-friendly accessor: call it at the top of each unit of work
+ * instead of getClient(), so transient drops heal without the caller
+ * writing catch-and-rebuild loops.
+ */
+ public function ensureLive(): ImapClient
+ {
+ if (!$this->isAlive()) {
+ $this->reconnect();
+ }
+
+ return $this->client;
+ }
+
+ /**
+ * Logs out and closes the underlying IMAP stream, returning the connection
+ * to its idle state so a later getClient() re-opens it. No-op when the
+ * client was never built.
+ */
+ public function disconnect(): void
+ {
+ $this->client?->logout();
+ $this->client = null;
+ }
+
+ /**
+ * Build the ImapClient from the account's connection parameters and the
+ * credential. Does not connect or authenticate.
+ *
+ * @throws \LogicException When the account is not an IMAP account.
+ * @throws \RuntimeException When the credential is not in a usable state.
+ */
+ private function buildClient(): ImapClient
+ {
+ if ($this->account->getProtocol() !== 'imap') {
+ // @todo POP3 accounts belong on an ImpPop3Connection; this class is
+ // IMAP-only until that counterpart exists.
+ throw new \LogicException(sprintf(
+ 'ImpImapConnection cannot serve protocol "%s" for account "%s".',
+ $this->account->getProtocol(),
+ $this->account->getId(),
+ ));
+ }
+
+ if ($this->credential->getState() !== HasCredentialsState::Present) {
+ throw new \RuntimeException(sprintf(
+ 'No usable credential for account "%s" (state: %s).',
+ $this->account->getId(),
+ $this->credential->getState()->name,
+ ));
+ }
+
+ $config = new ConnectionConfig(
+ hostspec: $this->account->getHostspec(),
+ port: $this->account->getPort(),
+ secure: $this->mapSecure($this->account->getSecure()),
+ context: $this->streamContext,
+ );
+
+ // @todo A future --insecure opt-in would pass
+ // saslPolicy: SaslPolicy::legacyCompatible() here so plaintext
+ // SASL against a non-TLS dev server is permitted. The default
+ // (secureDefaults) denies PLAIN/LOGIN without TLS.
+ return new ImapClient(
+ $config,
+ $this->credential->getSaslCredentials(),
+ $this->wrapDispatcher(),
+ );
+ }
+
+ /**
+ * Wrap the application dispatcher so the ImapClient's events arrive on the
+ * application bus tagged with this connection's account and user. Returns
+ * null when no dispatcher was supplied (the ImapClient then dispatches
+ * nothing).
+ */
+ private function wrapDispatcher(): ?EventDispatcherInterface
+ {
+ if ($this->dispatcher === null) {
+ return null;
+ }
+
+ return new AccountContextEventDispatcher(
+ $this->dispatcher,
+ $this->account->getId(),
+ $this->userId,
+ );
+ }
+
+ /**
+ * Map the account's transport-security token to a SecureMode.
+ *
+ * SecureMode is a backed string enum, so false (no encryption) must be
+ * mapped explicitly rather than passed to SecureMode::from().
+ *
+ * @param string|false $secure 'ssl', 'tls', 'tlsv1', or false.
+ */
+ private function mapSecure(string|false $secure): SecureMode
+ {
+ return match ($secure) {
+ false => SecureMode::None,
+ 'ssl' => SecureMode::Ssl,
+ 'tls' => SecureMode::Tls,
+ 'tlsv1' => SecureMode::Tlsv1,
+ };
+ }
+}
diff --git a/src/Mailbox/ImpMailboxAccountManager.php b/src/Mailbox/ImpMailboxAccountManager.php
new file mode 100755
index 000000000..5c27be377
--- /dev/null
+++ b/src/Mailbox/ImpMailboxAccountManager.php
@@ -0,0 +1,148 @@
+ $a->getPriority() <=> $b->getPriority()
+ );
+ $this->providers = $providers;
+ }
+
+ public function getAccounts(): array
+ {
+ $seen = [];
+ $accounts = [];
+
+ foreach ($this->providers as $provider) {
+ foreach ($provider->resolveAccounts() as $account) {
+ $id = $account->getId();
+ if (!array_key_exists($id, $seen)) {
+ $seen[$id] = true;
+ $accounts[] = $account;
+ }
+ }
+ }
+
+ return $accounts;
+ }
+
+ public function getAccount(string $id): MailboxAccount
+ {
+ foreach ($this->providers as $provider) {
+ foreach ($provider->resolveAccounts() as $account) {
+ if ($account->getId() === $id) {
+ return $account;
+ }
+ }
+ }
+
+ throw new MailboxAccountNotFound($id);
+ }
+
+ public function getConnection(MailboxAccount $account): MailboxConnection
+ {
+ if ($this->credentialSource === null) {
+ throw new \LogicException(
+ 'getConnection() needs a MailboxCredentialSource. This manager '
+ . 'was built without one; use getConnectionWith() with an '
+ . 'explicit credential (the CLI/daemon path).'
+ );
+ }
+
+ $userId = $this->credentialSource->ownerUserId();
+ if ($userId === null) {
+ throw new \RuntimeException(
+ 'Cannot open a mailbox connection: no authenticated Horde user '
+ . 'in this request.'
+ );
+ }
+
+ // Resolution decides which credential represents the account; it does
+ // not connect or log in. A missing secret surfaces later as a
+ // non-Present state at the explicit, lazy login moment, not here.
+ $credential = $this->credentialSource->resolve($account);
+
+ return $this->getConnectionWith($account, $credential, $userId);
+ }
+
+ public function getConnectionWith(
+ MailboxAccount $account,
+ MailboxCredential $credential,
+ string $userId,
+ ): MailboxConnection {
+ if ($credential->getAccountId() !== $account->getId()) {
+ throw new \InvalidArgumentException(sprintf(
+ 'Credential is for account "%s", not "%s".',
+ $credential->getAccountId(),
+ $account->getId(),
+ ));
+ }
+
+ // Cache by the composite (userId, accountId): the same backend yields
+ // the same account ID for every user, so the account ID alone would
+ // collide across users in a multi-user (daemon/worker) context.
+ $key = (string) ConnectionKey::of($userId, $account);
+
+ $cached = $this->cache->get($key);
+ if ($cached !== null) {
+ return $cached;
+ }
+
+ $connection = match ($account->getProtocol()) {
+ 'imap' => new ImpImapConnection($account, $credential, $userId),
+ // @todo 'pop3' => new ImpPop3Connection($account, $credential, $userId),
+ default => throw new \LogicException(sprintf(
+ 'No connection type for protocol "%s" (account "%s").',
+ $account->getProtocol(),
+ $account->getId(),
+ )),
+ };
+
+ $this->cache->set($key, $connection);
+
+ return $connection;
+ }
+}
diff --git a/src/Mailbox/LazyMailboxConnection.php b/src/Mailbox/LazyMailboxConnection.php
new file mode 100755
index 000000000..633c3d919
--- /dev/null
+++ b/src/Mailbox/LazyMailboxConnection.php
@@ -0,0 +1,48 @@
+isInitialized()) {
+ * // connection exists but no stream has been opened yet
+ * }
+ *
+ * Concrete implementations that are NOT lazy (pre-opened admin connections,
+ * test doubles with an already-live client) do not implement this interface.
+ * Their connections are always initialized by definition.
+ *
+ * Copyright 2026 The Horde Project (http://www.horde.org/)
+ *
+ * See the enclosed file LICENSE for license information (GPL). If you
+ * did not receive this file, see http://www.horde.org/licenses/gpl.
+ *
+ * @category Horde
+ * @copyright 2026 The Horde Project
+ * @license http://www.horde.org/licenses/gpl GPL
+ * @package IMP
+ */
+interface LazyMailboxConnection extends MailboxConnection
+{
+ /**
+ * Returns true if the underlying protocol client has been instantiated.
+ *
+ * False means the connection is idle — no stream has been opened and no
+ * credential has been presented to the server. It does NOT mean the
+ * account is unreachable.
+ *
+ * True means at least one connect attempt has been made. The stream may
+ * still drop later; this method reflects initialization state, not
+ * current liveness.
+ */
+ public function isInitialized(): bool;
+}
diff --git a/src/Mailbox/LiteralMailboxCredential.php b/src/Mailbox/LiteralMailboxCredential.php
new file mode 100755
index 000000000..e8355b9ba
--- /dev/null
+++ b/src/Mailbox/LiteralMailboxCredential.php
@@ -0,0 +1,72 @@
+accountId;
+ }
+
+ /**
+ * Always returns Present: the credential is available as long as this
+ * object exists. There is no invalidation path.
+ */
+ public function getState(): HasCredentialsState
+ {
+ return HasCredentialsState::Present;
+ }
+
+ /**
+ * Returns a PasswordCredentials instance wrapping the stored username
+ * and password. Safe to call without checking getState() first, but
+ * callers following the MailboxCredential contract will check anyway.
+ */
+ public function getSaslCredentials(): Credentials
+ {
+ return new PasswordCredentials($this->username, new PlainSecret($this->password));
+ }
+}
diff --git a/src/Mailbox/MailboxAccount.php b/src/Mailbox/MailboxAccount.php
new file mode 100755
index 000000000..dd713e6e8
--- /dev/null
+++ b/src/Mailbox/MailboxAccount.php
@@ -0,0 +1,91 @@
+bindFactory(
+ * MailboxAccountManager::class,
+ * MailboxAccountManagerFactory::class,
+ * 'create'
+ * );
+ *
+ * Resolves providers from the PROVIDERS class-name list. Each provider must be
+ * registered with its own factory in _bootstrap() before MailboxAccountManager
+ * is first resolved.
+ *
+ * ## Builder entrypoint (ad-hoc wiring)
+ *
+ * For diagnostic scripts, tests, or any context that needs to supply
+ * providers directly without going through the DI-configured list:
+ *
+ * $manager = MailboxAccountManagerFactory::fromScratch($injector)
+ * ->withProvider($adHocProvider) // pre-constructed instance
+ * ->withProviderClass(MyProvider::class) // resolved via injector at build()
+ * ->build();
+ *
+ * Both paths share the same assemble() step, keeping construction logic in
+ * one place.
+ *
+ * Copyright 2026 The Horde Project (http://www.horde.org/)
+ *
+ * See the enclosed file LICENSE for license information (GPL). If you
+ * did not receive this file, see http://www.horde.org/licenses/gpl.
+ *
+ * @category Horde
+ * @copyright 2026 The Horde Project
+ * @license http://www.horde.org/licenses/gpl GPL
+ * @package IMP
+ */
+final class MailboxAccountManagerFactory
+{
+ // -------------------------------------------------------------------------
+ // DI configuration: used by create() only
+ // -------------------------------------------------------------------------
+
+ /**
+ * Ordered list of MailboxProvider classes to resolve from the injector.
+ * Priority is determined by each provider's getPriority() return value;
+ * declaration order here is a tiebreaker only.
+ *
+ * @var list>
+ */
+ private const PROVIDERS = [
+ SiteAccountsProvider::class,
+ // @todo SessionCredentialProvider::class,
+ // @todo UserPrefsMailboxProvider::class,
+ // @todo OidcClaimsMailboxProvider::class,
+ ];
+
+ // -------------------------------------------------------------------------
+ // Builder state: populated by fromScratch() and with*() methods
+ // -------------------------------------------------------------------------
+
+ /**
+ * @param Injector|null $injector Stored by the builder path; null when
+ * instantiated by DI for create().
+ * @param list $providers Pre-constructed provider instances.
+ * @param list $providerClasses Provider class names. Resolved via injector at build() time.
+ */
+ public function __construct(
+ private readonly ?Injector $injector = null,
+ private readonly array $providers = [],
+ private readonly array $providerClasses = [],
+ ) {}
+
+ // -------------------------------------------------------------------------
+ // Default DI entrypoint
+ // -------------------------------------------------------------------------
+
+ /**
+ * Assembles ImpMailboxAccountManager from the PROVIDERS class-name list,
+ * resolving each via the injector.
+ *
+ * This is the method registered with bindFactory() in _bootstrap().
+ */
+ public function create(Injector $injector): MailboxAccountManager
+ {
+ return $this->assemble(
+ providers: array_map(
+ static fn(string $class) => $injector->get($class),
+ self::PROVIDERS
+ ),
+ credentialSource: $injector->get(MailboxCredentialSource::class),
+ );
+ }
+
+ // -------------------------------------------------------------------------
+ // Builder entrypoint + fluent methods
+ // -------------------------------------------------------------------------
+
+ /**
+ * Start a builder for an ad-hoc MailboxAccountManager.
+ *
+ * @return self Immutable builder with no providers.
+ */
+ public static function fromScratch(Injector $injector): self
+ {
+ return new self(injector: $injector);
+ }
+
+ /**
+ * Add a pre-constructed MailboxProvider instance.
+ *
+ * @return self New builder with the provider appended.
+ */
+ public function withProvider(MailboxProvider $provider): self
+ {
+ return new self(
+ injector: $this->injector,
+ providers: [...$this->providers, $provider],
+ providerClasses: $this->providerClasses,
+ );
+ }
+
+ /**
+ * Add a MailboxProvider by class name, resolved via the injector at build() time.
+ *
+ * @param class-string $class
+ * @return self New builder with the class appended.
+ */
+ public function withProviderClass(string $class): self
+ {
+ return new self(
+ injector: $this->injector,
+ providers: $this->providers,
+ providerClasses: [...$this->providerClasses, $class],
+ );
+ }
+
+ /**
+ * Assemble and return an ImpMailboxAccountManager from the ad-hoc list
+ * accumulated by the builder.
+ *
+ * @throws \LogicException When no Injector is stored (i.e. called on a
+ * DI-created instance rather than a fromScratch() chain).
+ */
+ public function build(): MailboxAccountManager
+ {
+ if ($this->injector === null) {
+ throw new \LogicException(
+ 'build() requires an Injector. Start the builder with '
+ . 'MailboxAccountManagerFactory::fromScratch($injector).'
+ );
+ }
+
+ return $this->assemble(
+ providers: [
+ ...$this->providers,
+ ...array_map(
+ fn(string $class) => $this->injector->get($class),
+ $this->providerClasses
+ ),
+ ],
+ );
+ }
+
+ // -------------------------------------------------------------------------
+ // Shared assembly — used by both create() and build()
+ // -------------------------------------------------------------------------
+
+ /**
+ * Construct the ImpMailboxAccountManager from the resolved provider array.
+ * Both entrypoints delegate here.
+ *
+ * @param list $providers
+ * @param MailboxCredentialSource|null $credentialSource Credential source for
+ * getConnection(). Null on the
+ * builder/CLI path, which uses
+ * getConnectionWith() explicitly.
+ */
+ private function assemble(
+ array $providers,
+ ?MailboxCredentialSource $credentialSource = null,
+ ): ImpMailboxAccountManager {
+ return new ImpMailboxAccountManager(
+ providers: $providers,
+ credentialSource: $credentialSource,
+ );
+ }
+}
diff --git a/src/Mailbox/MailboxAccountNotFound.php b/src/Mailbox/MailboxAccountNotFound.php
new file mode 100755
index 000000000..9828ff2e9
--- /dev/null
+++ b/src/Mailbox/MailboxAccountNotFound.php
@@ -0,0 +1,50 @@
+accountId;
+ }
+}
diff --git a/src/Mailbox/MailboxCapability.php b/src/Mailbox/MailboxCapability.php
new file mode 100755
index 000000000..93aa462ee
--- /dev/null
+++ b/src/Mailbox/MailboxCapability.php
@@ -0,0 +1,57 @@
+
+ * @category Horde
+ * @copyright 2026 The Horde Project
+ * @license http://www.horde.org/licenses/gpl GPL
+ * @package IMP
+ */
+interface MailboxCredentialSource
+{
+ /**
+ * The Horde user id that owns connections in this request, or null when
+ * no authenticated user is available.
+ *
+ * This identifies the connection owner for cache-keying and is distinct
+ * from the mailbox username carried inside the credential.
+ */
+ public function ownerUserId(): ?string;
+
+ /**
+ * Produce the MailboxCredential representing the given account for the
+ * current request.
+ *
+ * Returns a credential whose getState() may be NeverHad or Invalidated
+ * when no usable secret exists yet; it does not throw for a missing
+ * secret. The returned credential's getAccountId() matches the account.
+ *
+ * @param MailboxAccount $account The account to authenticate.
+ */
+ public function resolve(MailboxAccount $account): MailboxCredential;
+}
diff --git a/src/Mailbox/MailboxProvider.php b/src/Mailbox/MailboxProvider.php
new file mode 100755
index 000000000..63b6208c6
--- /dev/null
+++ b/src/Mailbox/MailboxProvider.php
@@ -0,0 +1,73 @@
+ensureLive(); // reconnect + re-auth if needed
+ * }
+ *
+ * Reconnecting re-reads the MailboxCredential, so a transparently refreshed
+ * OAuth token or a rotated password is picked up on reconnect. This is the
+ * same mechanism that recovers from a dropped socket: both go through a clean
+ * rebuild rather than mutating connection state in place.
+ *
+ * Non-network connections (feed/RSS accounts, test doubles with a fixed
+ * client) do not implement this interface.
+ *
+ * Copyright 2026 The Horde Project (http://www.horde.org/)
+ *
+ * See the enclosed file LICENSE for license information (GPL). If you
+ * did not receive this file, see http://www.horde.org/licenses/gpl.
+ *
+ * @category Horde
+ * @copyright 2026 The Horde Project
+ * @license http://www.horde.org/licenses/gpl GPL
+ * @package IMP
+ */
+interface RecoverableConnection extends MailboxConnection
+{
+ /**
+ * Returns true if the underlying stream is open AND authenticated right now.
+ *
+ * This is a liveness probe, not an initialization flag: it may perform a
+ * lightweight server round-trip (e.g. NOOP). It MUST NOT silently open a
+ * fresh unauthenticated stream as a side effect of answering — a probe that
+ * reconnects-without-login would corrupt the authenticated invariant. An
+ * idle, never-built, or logged-out connection returns false rather than
+ * connecting.
+ *
+ * False does not mean the account is unreachable; it means the caller
+ * should reconnect() (or ensureLive()) before issuing commands.
+ */
+ public function isAlive(): bool;
+
+ /**
+ * Tears down any existing stream and establishes a fresh authenticated one.
+ *
+ * Re-reads the MailboxCredential, so token refreshes and password rotations
+ * take effect here. Safe to call whether or not a stream is currently open.
+ *
+ * @throws \Horde\Imap\Client\Exception\ConnectionException if the stream cannot be opened.
+ * @throws \Horde\Imap\Client\Exception\AuthenticationException if authentication fails.
+ */
+ public function reconnect(): void;
+}
diff --git a/src/Mailbox/SessionCredentialSource.php b/src/Mailbox/SessionCredentialSource.php
new file mode 100644
index 000000000..81cd82def
--- /dev/null
+++ b/src/Mailbox/SessionCredentialSource.php
@@ -0,0 +1,62 @@
+
+ * @category Horde
+ * @copyright 2026 The Horde Project
+ * @license http://www.horde.org/licenses/gpl GPL
+ * @package IMP
+ */
+final class SessionCredentialSource implements MailboxCredentialSource
+{
+ /**
+ * @param SessionAccess $session The request-scoped session accessor.
+ * @param AuthCredentialStore $store Session-resident credential store.
+ * @param string $app The application whose session
+ * credential slot holds the mailbox
+ * username/password. Defaults to 'imp'.
+ */
+ public function __construct(
+ private readonly SessionAccess $session,
+ private readonly AuthCredentialStore $store,
+ private readonly string $app = 'imp',
+ ) {}
+
+ public function ownerUserId(): ?string
+ {
+ return $this->session->getAuthId();
+ }
+
+ public function resolve(MailboxAccount $account): MailboxCredential
+ {
+ return new SessionPasswordCredential(
+ $this->store,
+ $account->getId(),
+ $this->app
+ );
+ }
+}
diff --git a/src/Mailbox/SessionPasswordCredential.php b/src/Mailbox/SessionPasswordCredential.php
new file mode 100644
index 000000000..4b20f9cac
--- /dev/null
+++ b/src/Mailbox/SessionPasswordCredential.php
@@ -0,0 +1,111 @@
+
+ * @category Horde
+ * @copyright 2026 The Horde Project
+ * @license http://www.horde.org/licenses/gpl GPL
+ * @package IMP
+ */
+final class SessionPasswordCredential implements MailboxCredential
+{
+ /**
+ * @param AuthCredentialStore $store Session-resident credential store.
+ * @param string $accountId The account ID this credential
+ * authenticates. Must match the
+ * target MailboxAccount::getId().
+ * @param string $app The application whose session
+ * credential slot holds the mailbox
+ * username/password (e.g. 'imp').
+ */
+ public function __construct(
+ private readonly AuthCredentialStore $store,
+ private readonly string $accountId,
+ private readonly string $app,
+ ) {}
+
+ public function getAccountId(): string
+ {
+ return $this->accountId;
+ }
+
+ /**
+ * Reflects the live session credential state for the application. Read
+ * from AuthCredentialStore on every call so a mid-session change (wipe,
+ * invalidation) is observed rather than cached.
+ */
+ public function getState(): HasCredentialsState
+ {
+ return $this->store->getState($this->app);
+ }
+
+ /**
+ * Builds PasswordCredentials from the session-stored username and password.
+ *
+ * Re-reads the store rather than trusting a construction-time snapshot: if
+ * the session password is no longer Present, throws instead of returning
+ * stale credentials, per the MailboxCredential contract.
+ *
+ * @throws RuntimeException if the credential is not Present, or the stored
+ * array is missing the expected keys.
+ */
+ public function getSaslCredentials(): Credentials
+ {
+ $result = $this->store->getOrExplain($this->app);
+
+ if ($result->state !== HasCredentialsState::Present
+ || $result->credentials === null) {
+ throw new RuntimeException(sprintf(
+ 'No session password available for account "%s" (state: %s).',
+ $this->accountId,
+ $result->state->value
+ ));
+ }
+
+ $credentials = $result->credentials;
+ if (!isset($credentials['userId'], $credentials['password'])
+ || !is_string($credentials['password'])) {
+ throw new RuntimeException(sprintf(
+ 'Session credential for account "%s" is missing a usable '
+ . 'username/password pair.',
+ $this->accountId
+ ));
+ }
+
+ return new PasswordCredentials(
+ (string) $credentials['userId'],
+ new PlainSecret($credentials['password'])
+ );
+ }
+}
diff --git a/src/Mailbox/SiteAccountsProvider.php b/src/Mailbox/SiteAccountsProvider.php
new file mode 100755
index 000000000..dc91dcb73
--- /dev/null
+++ b/src/Mailbox/SiteAccountsProvider.php
@@ -0,0 +1,177 @@
+
+ */
+ public function resolveAccounts(): array
+ {
+ $accounts = [];
+
+ foreach ($this->backendState->listBackends(includeDisabled: true) as $key => $config) {
+ $disabled = !empty($config['disabled']);
+ $forced = in_array($key, $this->forcedBackendKeys, true);
+
+ if ($disabled && !$forced) {
+ continue;
+ }
+
+ $accounts[] = $this->buildAccount($key, $config);
+ }
+
+ return $accounts;
+ }
+
+ // -------------------------------------------------------------------------
+ // Introspection
+ // -------------------------------------------------------------------------
+
+ /**
+ * List all backends matching the given filter as SiteMailboxAccount instances.
+ *
+ * Unlike resolveAccounts(), this method is a pure view of the backends.php
+ * state: forced backend keys have no effect, and no session is consulted.
+ * Use BackendFilter::Disabled to enumerate what has been turned off;
+ * use BackendFilter::All for a complete inventory.
+ *
+ * @return list
+ */
+ public function list(BackendFilter $filter): array
+ {
+ $accounts = [];
+
+ foreach ($this->backendState->listBackends(includeDisabled: true) as $key => $config) {
+ $disabled = !empty($config['disabled']);
+
+ $include = match ($filter) {
+ BackendFilter::Enabled => !$disabled,
+ BackendFilter::Disabled => $disabled,
+ BackendFilter::All => true,
+ };
+
+ if ($include) {
+ $accounts[] = $this->buildAccount($key, $config);
+ }
+ }
+
+ return $accounts;
+ }
+
+ // -------------------------------------------------------------------------
+ // Internals
+ // -------------------------------------------------------------------------
+
+ /**
+ * Build a SiteMailboxAccount from a raw backend config array.
+ *
+ * Capabilities are inferred from the protocol:
+ * imap: FolderManagement, EfficientSearch, MessageFlags, MessageUpload
+ * pop3: (none — POP3 exposes no persistent folder tree or flag storage)
+ */
+ private function buildAccount(string $key, array $config): SiteMailboxAccount
+ {
+ $protocol = $config['protocol'] ?? 'imap';
+
+ $capabilities = match ($protocol) {
+ 'pop3' => [],
+ default => [
+ MailboxCapability::FolderManagement,
+ MailboxCapability::EfficientSearch,
+ MailboxCapability::MessageFlags,
+ MailboxCapability::MessageUpload,
+ ],
+ };
+
+ return new SiteMailboxAccount(
+ id: self::PROVIDER_ID . ':' . $key,
+ label: $config['name'] ?? $key,
+ backendKey: $key,
+ protocol: $protocol,
+ capabilities: $capabilities,
+ hostspec: $config['hostspec'] ?? 'localhost',
+ port: isset($config['port']) ? (int) $config['port'] : null,
+ secure: $config['secure'] ?? 'tls',
+ );
+ }
+}
diff --git a/src/Mailbox/SiteAccountsProviderFactory.php b/src/Mailbox/SiteAccountsProviderFactory.php
new file mode 100755
index 000000000..216397cb4
--- /dev/null
+++ b/src/Mailbox/SiteAccountsProviderFactory.php
@@ -0,0 +1,155 @@
+bindFactory(
+ * SiteAccountsProvider::class,
+ * SiteAccountsProviderFactory::class,
+ * 'create'
+ * );
+ *
+ * create() produces a provider that picks up all non-disabled backends.
+ *
+ * ## Builder entrypoint
+ *
+ * Use fromScratch() when specific disabled backends must be included:
+ *
+ * $provider = SiteAccountsProviderFactory::fromScratch($injector)
+ * ->withBackendKey('staging_imap')
+ * ->build();
+ *
+ * withBackendKey() may be chained any number of times. Each call returns
+ * a new immutable instance. Duplicate keys are harmless.
+ *
+ * Both paths delegate to the same assemble() step, so the resulting
+ * SiteAccountsProvider is identical in type regardless of which path
+ * produced it.
+ *
+ * Copyright 2026 The Horde Project (http://www.horde.org/)
+ *
+ * See the enclosed file LICENSE for license information (GPL). If you
+ * did not receive this file, see http://www.horde.org/licenses/gpl.
+ *
+ * @category Horde
+ * @copyright 2026 The Horde Project
+ * @license http://www.horde.org/licenses/gpl GPL
+ * @package IMP
+ */
+final class SiteAccountsProviderFactory
+{
+ /**
+ * @param Injector|null $injector Stored by the builder path; null when instantiated
+ * by DI for the create() entrypoint.
+ * @param string[] $forcedBackendKeys Keys registered via withBackendKey(). Resolved
+ * into the provider at build() or assemble() time.
+ */
+ public function __construct(
+ private readonly ?Injector $injector = null,
+ private readonly array $forcedBackendKeys = [],
+ ) {}
+
+ // -------------------------------------------------------------------------
+ // Default DI entrypoint
+ // -------------------------------------------------------------------------
+
+ /**
+ * Produces a SiteAccountsProvider covering all non-disabled backends.
+ *
+ * This is the method registered with bindFactory() in _bootstrap().
+ */
+ public function create(Injector $injector): SiteAccountsProvider
+ {
+ return $this->assemble($injector, []);
+ }
+
+ // -------------------------------------------------------------------------
+ // Builder entrypoint and fluent methods
+ // -------------------------------------------------------------------------
+
+ /**
+ * Start a builder that can force disabled backends into the provider.
+ *
+ * @return self Immutable builder with no forced backend keys.
+ */
+ public static function fromScratch(Injector $injector): self
+ {
+ return new self(injector: $injector);
+ }
+
+ /**
+ * Force a backend into the provider's resolveAccounts() output, even if
+ * backends.php marks it disabled.
+ *
+ * Intended for diagnostic scripts and controlled test setups.
+ *
+ * @return self New builder with the key appended.
+ */
+ public function withBackendKey(string $key): self
+ {
+ return new self(
+ injector: $this->injector,
+ forcedBackendKeys: [...$this->forcedBackendKeys, $key],
+ );
+ }
+
+ /**
+ * Assemble and return a SiteAccountsProvider from the accumulated state.
+ *
+ * @throws \LogicException When called on a DI-created instance that has
+ * no stored Injector. Use fromScratch($injector)
+ * to start the builder.
+ * @throws \InvalidArgumentException When a forced backend key is not present
+ * in backends.php.
+ */
+ public function build(): SiteAccountsProvider
+ {
+ if ($this->injector === null) {
+ throw new \LogicException(
+ 'build() requires an Injector. '
+ . 'Start the builder with SiteAccountsProviderFactory::fromScratch($injector).'
+ );
+ }
+
+ return $this->assemble($this->injector, $this->forcedBackendKeys);
+ }
+
+ // -------------------------------------------------------------------------
+ // Shared assembly: used by both create() and build()
+ // -------------------------------------------------------------------------
+
+ /**
+ * @param string[] $forcedBackendKeys
+ * @throws \InvalidArgumentException When a forced key is absent from backends.php.
+ */
+ private function assemble(Injector $injector, array $forcedBackendKeys): SiteAccountsProvider
+ {
+ $backendState = $injector->get(BackendConfigLoader::class)->load('imp', 'backends.php', 'servers');
+
+ foreach ($forcedBackendKeys as $key) {
+ if ($backendState->getBackend($key) === null) {
+ throw new \InvalidArgumentException(sprintf(
+ 'Backend key "%s" does not exist in backends.php.',
+ $key,
+ ));
+ }
+ }
+
+ return new SiteAccountsProvider(
+ backendState: $backendState,
+ forcedBackendKeys: $forcedBackendKeys,
+ );
+ }
+}
diff --git a/src/Mailbox/SiteMailboxAccount.php b/src/Mailbox/SiteMailboxAccount.php
new file mode 100755
index 000000000..858617502
--- /dev/null
+++ b/src/Mailbox/SiteMailboxAccount.php
@@ -0,0 +1,118 @@
+ $capabilities Capabilities inferred from protocol.
+ * @param string $hostspec Mail server hostname or IP address.
+ * @param int|null $port TCP port, or null to use the protocol default.
+ * @param string|false $secure 'ssl', 'tls', 'tlsv1', or false for no encryption.
+ */
+ public function __construct(
+ private readonly string $id,
+ private readonly string $label,
+ private readonly string $backendKey,
+ private readonly string $protocol,
+ private readonly array $capabilities,
+ private readonly string $hostspec = 'localhost',
+ private readonly int|null $port = null,
+ private readonly string|false $secure = 'tls',
+ ) {}
+
+ public function getId(): string
+ {
+ return $this->id;
+ }
+
+ public function getLabel(): string
+ {
+ return $this->label;
+ }
+
+ public function getProviderId(): string
+ {
+ return SiteAccountsProvider::PROVIDER_ID;
+ }
+
+ /**
+ * @return list
+ */
+ public function getCapabilities(): array
+ {
+ return $this->capabilities;
+ }
+
+ /**
+ * The backends.php key this account was created from.
+ */
+ public function getBackendKey(): string
+ {
+ return $this->backendKey;
+ }
+
+ /**
+ * Protocol identifier: 'imap' or 'pop3'.
+ */
+ public function getProtocol(): string
+ {
+ return $this->protocol;
+ }
+
+ /**
+ * Mail server hostname or IP address.
+ */
+ public function getHostspec(): string
+ {
+ return $this->hostspec;
+ }
+
+ /**
+ * TCP port, or null when the protocol default should be used.
+ */
+ public function getPort(): ?int
+ {
+ return $this->port;
+ }
+
+ /**
+ * Transport security: 'ssl', 'tls', 'tlsv1', or false for no encryption.
+ *
+ * @return string|false
+ */
+ public function getSecure(): string|false
+ {
+ return $this->secure;
+ }
+}
diff --git a/src/Mailboxes/AuthTestController.php b/src/Mailboxes/AuthTestController.php
new file mode 100644
index 000000000..5b0f7435a
--- /dev/null
+++ b/src/Mailboxes/AuthTestController.php
@@ -0,0 +1,206 @@
+getMethod();
+ $body = $request->getParsedBody() ?? [];
+ // Handle POST - provision from session
+ if ($method === 'POST' && isset($body['backend_id'])) {
+ return $this->provisionFromSession($body['backend_id']);
+ }
+
+ // GET - show status
+ return $this->showStatus($request);
+ }
+
+ private function showStatus(ServerRequestInterface $request): ResponseInterface
+ {
+ $userId = $this->registry->getAuth();
+ $backends = $this->backendConfig->toArray();
+ $results = [];
+ $message = $request->getQueryParams()['message'] ?? null;
+ foreach ($backends as $backendId => $backend) {
+ if (isset($backend['disabled']) && $backend['disabled']) {
+ continue;
+ }
+
+ $credentialSystem = $backend['credential_system'] ?? 'password';
+
+ // Skip OAuth backends for now
+ if ($credentialSystem === 'oauth') {
+ continue;
+ }
+
+ $purpose = ServicePurpose::of('imap', GrantStrategy::Isolated);
+
+ try {
+ $credential = $this->store->find($userId, $backendId, $purpose);
+
+ if ($credential) {
+ $structured = $credential->asStructured();
+ $results[] = [
+ 'backend_id' => $backendId,
+ 'backend_name' => $backend['name'] ?? $backendId,
+ 'status' => 'found',
+ 'username' => $structured['username'] ?? 'N/A',
+ 'has_password' => isset($structured['password']),
+ 'created_at' => date('Y-m-d H:i:s', $credential->createdAt()),
+ ];
+ } else {
+ $results[] = [
+ 'backend_id' => $backendId,
+ 'backend_name' => $backend['name'] ?? $backendId,
+ 'status' => 'not_found',
+ ];
+ }
+ } catch (\Throwable $e) {
+ $results[] = [
+ 'backend_id' => $backendId,
+ 'backend_name' => $backend['name'] ?? $backendId,
+ 'status' => 'error',
+ 'error' => $e->getMessage(),
+ ];
+ }
+ }
+
+ $html = $this->renderView($results, $message);
+ return $this->htmlResponse($html);
+ }
+
+ private function provisionFromSession(string $backendId): ResponseInterface
+ {
+ $userId = $this->registry->getAuth();
+ $creds = $this->registry->getAuthCredential();
+ $password = $creds['password'] ?? null;
+ $purpose = ServicePurpose::of('imap', GrantStrategy::Isolated);
+
+ $provisioner = new SessionToCredentialStoreProvisioner(
+ $this->authCredentials,
+ $this->store
+ );
+
+ try {
+ $result = $provisioner->provision($userId, $backendId, $purpose);
+ $message = 'Provisioning result: ' . $result->action->name;
+ } catch (\Throwable $e) {
+ $message = 'Provisioning failed: ' . $e->getMessage();
+ }
+
+ // Redirect back to GET with message
+ // TODO: Use the routes framework instead of this hardcoding.
+ return $this->redirect('/imp/mailboxes/authtest/?message=' . urlencode($message));
+ }
+
+ private function renderView(array $results, ?string $message): string
+ {
+ ob_start();
+ ?>
+
+
+
+
+ IMP Auth Test - Password Credentials
+
+
+
IMP Auth Test - Password Credentials
+
+
+
+
+
+ Testing password credential storage for mail backends.
+
+ Backend Status
+
+
+ No backends configured.
+
+
+
+
+ | Backend ID |
+ Backend Name |
+ Status |
+ Details |
+ Action |
+
+
+
+
+
+ |
+ |
+ |
+
+
+ Username:
+ Has password:
+ Created:
+
+ No credential set
+
+ Error:
+
+ |
+
+
+ registry->getAuth(); $creds = $this->registry->getAuthCredential(); echo empty($creds['password']) ? ' (No password in session)' : ' (Password in session)'; ?>
+
+
+ —
+
+ |
+
+
+
+
+
+
+
+ This is a test page for the password credential system.
+
+
+