2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 Waqas Hussain
4 -- Copyright (C) 2014 Daurnimator
6 -- This project is MIT/X11 licensed. Please see the
7 -- COPYING file in the source package for more information.
10 local select = select;
11 local pairs, ipairs = pairs, ipairs;
13 local setmetatable = setmetatable;
15 local dataform = require "util.dataforms";
16 local iterators = require "util.iterators";
17 local jid_split = require "util.jid".split;
18 local jid_bare = require "util.jid".bare;
19 local jid_prep = require "util.jid".prep;
20 local st = require "util.stanza";
21 local log = require "util.logger".init("mod_muc");
22 local base64 = require "util.encodings".base64;
23 local md5 = require "util.hashes".md5;
25 local occupant_lib = module:require "muc/occupant"
26 local muc_util = module:require "muc/util";
27 local is_kickable_error = muc_util.is_kickable_error;
28 local valid_roles, valid_affiliations = muc_util.valid_roles, muc_util.valid_affiliations;
31 room_mt.__index = room_mt;
33 function room_mt:__tostring()
34 return "MUC room ("..self.jid..")";
37 function room_mt:get_occupant_jid(real_jid)
38 return self._jid_nick[real_jid]
41 function room_mt:get_default_role(affiliation)
42 local role = module:fire_event("muc-get-default-role", {
44 affiliation = affiliation;
45 affiliation_rank = valid_affiliations[affiliation or "none"];
47 return role, valid_roles[role or "none"];
49 module:hook("muc-get-default-role", function(event)
50 if event.affiliation_rank >= valid_affiliations.admin then
52 elseif event.affiliation_rank >= valid_affiliations.member then
56 module:hook("muc-get-default-role", function(event)
57 if not event.affiliation then
58 return event.room:get_moderated() and "visitor" or "participant";
62 --- Occupant functions
63 function room_mt:new_occupant(bare_real_jid, nick)
64 local occupant = occupant_lib.new(bare_real_jid, nick);
65 local affiliation = self:get_affiliation(bare_real_jid);
66 occupant.role = self:get_default_role(affiliation);
70 function room_mt:get_occupant_by_nick(nick)
71 local occupant = self._occupants[nick];
72 if occupant == nil then return nil end
73 return occupant_lib.copy(occupant);
77 local function next_copied_occupant(occupants, occupant_jid)
78 local next_occupant_jid, raw_occupant = next(occupants, occupant_jid);
79 if next_occupant_jid == nil then return nil end
80 return next_occupant_jid, occupant_lib.copy(raw_occupant);
82 function room_mt:each_occupant(read_only)
83 return next_copied_occupant, self._occupants, nil;
87 function room_mt:get_occupant_by_real_jid(real_jid)
88 local occupant_jid = self:get_occupant_jid(real_jid);
89 if occupant_jid == nil then return nil end
90 return self:get_occupant_by_nick(occupant_jid);
93 function room_mt:save_occupant(occupant)
94 occupant = occupant_lib.copy(occupant); -- So that occupant can be modified more
95 local id = occupant.nick
97 -- Need to maintain _jid_nick secondary index
98 local old_occupant = self._occupants[id];
100 for real_jid in pairs(old_occupant.sessions) do
101 self._jid_nick[real_jid] = nil;
104 if occupant.role ~= nil and next(occupant.sessions) then
105 for real_jid, presence in occupant:each_session() do
106 self._jid_nick[real_jid] = occupant.nick;
111 self._occupants[id] = occupant
114 function room_mt:route_to_occupant(occupant, stanza)
115 local to = stanza.attr.to;
116 for jid, pr in occupant:each_session() do
117 if pr.attr.type ~= "unavailable" then
118 stanza.attr.to = jid;
119 self:route_stanza(stanza);
125 -- actor is the attribute table
126 local function add_item(x, affiliation, role, jid, nick, actor, reason)
127 x:tag("item", {affiliation = affiliation; role = role; jid = jid; nick = nick;})
129 x:tag("actor", actor):up()
132 x:tag("reason"):text(reason):up()
138 -- actor is (real) jid
139 function room_mt:build_item_list(occupant, x, is_anonymous, nick, actor, reason)
140 local affiliation = self:get_affiliation(occupant.bare_jid) or "none";
141 local role = occupant.role or "none";
144 actor_attr = {nick = select(3,jid_split(self:get_occupant_jid(actor)))};
147 add_item(x, affiliation, role, nil, nick, actor_attr, reason);
150 actor_attr.jid = actor;
152 for real_jid, session in occupant:each_session() do
153 add_item(x, affiliation, role, real_jid, nick, actor_attr, reason);
159 function room_mt:broadcast_message(stanza)
160 module:fire_event("muc-broadcast-message", {room = self, stanza = stanza});
161 self:broadcast(stanza);
164 -- Broadcast a stanza to all occupants in the room.
165 -- optionally checks conditional called with (nick, occupant)
166 function room_mt:broadcast(stanza, cond_func)
167 for nick, occupant in self:each_occupant() do
168 if cond_func == nil or cond_func(nick, occupant) then
169 self:route_to_occupant(occupant, stanza)
174 local function can_see_real_jids(whois, occupant)
175 if whois == "anyone" then
177 elseif whois == "moderators" then
178 return valid_roles[occupant.role or "none"] >= valid_roles.moderator;
182 local function get_base_presence(occupant)
183 if occupant.role ~= nil then
184 -- Try to use main jid's presence
185 local pr = occupant:get_presence();
190 return st.presence {from = occupant.nick; type = "unavailable";};
193 -- Broadcasts an occupant's presence to the whole room
194 -- Takes the x element that goes into the stanzas
195 function room_mt:publicise_occupant_status(occupant, base_x, nick, actor, reason)
196 -- Build real jid and (optionally) occupant jid template presences
197 local function get_presence(is_anonymous)
198 local x = st.clone(base_x);
199 self:build_item_list(occupant, x, is_anonymous, nick, actor, reason);
200 return get_base_presence(occupant):add_child(x), x;
202 local full_p, full_x = get_presence(false);
203 local anon_p, anon_x;
204 local function get_anon_p()
205 if anon_p == nil then
206 anon_p, anon_x = get_presence(true);
208 return anon_p, anon_x;
211 local whois = self:get_whois();
214 for nick, n_occupant in self:each_occupant() do
215 if nick ~= occupant.nick then
217 if can_see_real_jids(whois, occupant) or occupant.bare_jid == n_occupant.bare_jid then
222 self:route_to_occupant(n_occupant, pr);
226 -- Presences for occupant itself
227 full_x:tag("status", {code = "110";}):up();
228 if occupant.role == nil then
229 -- They get an unavailable
230 self:route_to_occupant(occupant, full_p);
232 -- use their own presences as templates
233 for full_jid, pr in occupant:each_session() do
235 pr.attr.to = full_jid;
236 -- You can always see your own full jids
237 pr:add_child(full_x);
238 self:route_stanza(pr);
243 function room_mt:send_occupant_list(to, filter)
244 local to_bare = jid_bare(to);
245 local is_anonymous = true;
246 local whois = self:get_whois();
247 if whois ~= "anyone" then
248 local affiliation = self:get_affiliation(to);
249 if affiliation ~= "admin" and affiliation ~= "owner" then
250 local occupant = self:get_occupant_by_real_jid(to);
251 if not occupant or can_see_real_jids(whois, occupant) then
252 is_anonymous = false;
256 for occupant_jid, occupant in self:each_occupant() do
257 if filter == nil or filter(occupant_jid, occupant) then
258 local x = st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
259 self:build_item_list(occupant, x, is_anonymous and to_bare ~= occupant.bare_jid); -- can always see your own jids
260 local pres = st.clone(occupant:get_presence());
263 self:route_stanza(pres);
268 function room_mt:get_disco_info(stanza)
269 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#info");
270 local form = dataform.new {
271 { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" };
273 module:fire_event("muc-disco#info", {room = self; reply = reply; form = form;});
274 reply:add_child(form:form(nil, "result"));
277 module:hook("muc-disco#info", function(event)
278 event.reply:tag("feature", {var = "http://jabber.org/protocol/muc"}):up();
280 module:hook("muc-disco#info", function(event)
281 event.reply:tag("feature", {var = event.room:get_moderated() and "muc_moderated" or "muc_unmoderated"}):up();
283 module:hook("muc-disco#info", function(event)
284 event.reply:tag("feature", {var = event.room:get_hidden() and "muc_hidden" or "muc_public"}):up();
286 module:hook("muc-disco#info", function(event)
287 local count = iterators.count(event.room:each_occupant());
288 table.insert(event.form, { name = "muc#roominfo_occupants", label = "Number of occupants", value = tostring(count) });
291 function room_mt:get_disco_items(stanza)
292 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
293 for room_jid in self:each_occupant() do
294 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
299 function room_mt:get_subject()
300 return self._data['subject'], self._data['subject_from']
302 local function create_subject_message(from, subject)
303 return st.message({from = from; type = "groupchat"})
304 :tag('subject'):text(subject):up();
306 function room_mt:send_subject(to)
307 local msg = create_subject_message(self:get_subject());
309 self:route_stanza(msg);
311 function room_mt:set_subject(current_nick, subject)
312 if subject == "" then subject = nil; end
313 self._data['subject'] = subject;
314 self._data['subject_from'] = current_nick;
315 if self.save then self:save(); end
316 local msg = create_subject_message(current_nick, subject);
317 self:broadcast_message(msg);
321 function room_mt:handle_kickable(origin, stanza)
322 local real_jid = stanza.attr.from;
323 local occupant = self:get_occupant_by_real_jid(real_jid);
324 if occupant == nil then return nil; end
325 local type, condition, text = stanza:get_error();
326 local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
328 error_message = error_message..": "..text;
330 occupant:set_session(real_jid, st.presence({type="unavailable"})
331 :tag('status'):text(error_message));
332 self:save_occupant(occupant);
333 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
334 :tag("status", {code = "307"})
335 self:publicise_occupant_status(occupant, x);
339 function room_mt:set_moderated(moderated)
340 moderated = moderated and true or nil;
341 if self._data.moderated ~= moderated then
342 self._data.moderated = moderated;
343 if self.save then self:save(true); end
346 function room_mt:get_moderated()
347 return self._data.moderated;
349 function room_mt:set_hidden(hidden)
350 hidden = hidden and true or nil;
351 if self._data.hidden ~= hidden then
352 self._data.hidden = hidden;
353 if self.save then self:save(true); end
356 function room_mt:get_hidden()
357 return self._data.hidden;
359 function room_mt:get_public()
360 return not self:get_hidden();
362 function room_mt:set_public(public)
363 return self:set_hidden(not public);
365 function room_mt:set_changesubject(changesubject)
366 changesubject = changesubject and true or nil;
367 if self._data.changesubject ~= changesubject then
368 self._data.changesubject = changesubject;
369 if self.save then self:save(true); end
372 function room_mt:get_changesubject()
373 return self._data.changesubject;
376 -- Give the room creator owner affiliation
377 module:hook("muc-room-pre-create", function(event)
378 event.room:set_affiliation(true, jid_bare(event.stanza.attr.from), "owner");
382 -- check if user is banned
383 module:hook("muc-occupant-pre-join", function(event)
384 local room, stanza = event.room, event.stanza;
385 local affiliation = room:get_affiliation(stanza.attr.from);
386 if affiliation == "outcast" then
387 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
388 reply.tags[1].attr.code = "403";
389 event.origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
394 -- Send occupant list to newly joined user
395 module:hook("muc-occupant-joined", function(event)
396 local real_jid = event.stanza.attr.from;
397 event.room:send_occupant_list(real_jid, function(nick, occupant)
398 -- Don't include self
399 return occupant:get_presence(real_jid) == nil;
403 -- Send subject to joining user
404 module:hook("muc-occupant-joined", function(event)
405 event.room:send_subject(event.stanza.attr.from);
408 function room_mt:handle_presence_to_occupant(origin, stanza)
409 local type = stanza.attr.type;
410 if type == "error" then -- error, kick em out!
411 return self:handle_kickable(origin, stanza)
412 elseif type == nil or type == "unavailable" then
413 local real_jid = stanza.attr.from;
414 local bare_jid = jid_bare(real_jid);
415 local orig_occupant, dest_occupant;
416 local is_new_room = next(self._affiliations) == nil;
418 if type == "unavailable" then return true; end -- Unavailable from someone not in the room
419 if module:fire_event("muc-room-pre-create", {
423 }) then return true; end
425 orig_occupant = self:get_occupant_by_real_jid(real_jid);
426 if type == "unavailable" and orig_occupant == nil then return true; end -- Unavailable from someone not in the room
428 local is_first_dest_session;
429 if type == "unavailable" then
430 -- dest_occupant = nil
431 elseif orig_occupant and orig_occupant.nick == stanza.attr.to then -- Just a presence update
432 log("debug", "presence update for %s from session %s", orig_occupant.nick, real_jid);
433 dest_occupant = orig_occupant;
435 local dest_jid = stanza.attr.to;
436 dest_occupant = self:get_occupant_by_nick(dest_jid);
437 if dest_occupant == nil then
438 log("debug", "no occupant found for %s; creating new occupant object for %s", dest_jid, real_jid);
439 is_first_dest_session = true;
440 dest_occupant = self:new_occupant(bare_jid, dest_jid);
442 is_first_dest_session = false;
445 local is_last_orig_session;
446 if orig_occupant ~= nil then
447 -- Is there are least 2 sessions?
448 local iter, ob, last = orig_occupant:each_session();
449 is_last_orig_session = iter(ob, iter(ob, last)) == nil;
452 local event, event_name = {
456 is_first_session = is_first_dest_session;
457 is_last_session = is_last_orig_session;
459 if orig_occupant == nil then
460 event_name = "muc-occupant-pre-join";
461 event.is_new_room = is_new_room;
462 elseif dest_occupant == nil then
463 event_name = "muc-occupant-pre-leave";
465 event_name = "muc-occupant-pre-change";
467 if module:fire_event(event_name, event) then return true; end
469 -- Check for nick conflicts
470 if dest_occupant ~= nil and not is_first_dest_session and bare_jid ~= jid_bare(dest_occupant.bare_jid) then -- new nick or has different bare real jid
471 log("debug", "%s couldn't join due to nick conflict: %s", real_jid, dest_occupant.nick);
472 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
473 reply.tags[1].attr.code = "409";
474 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
478 -- Send presence stanza about original occupant
479 if orig_occupant ~= nil and orig_occupant ~= dest_occupant then
480 local orig_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
482 if dest_occupant == nil then -- Session is leaving
483 log("debug", "session %s is leaving occupant %s", real_jid, orig_occupant.nick);
484 orig_occupant:set_session(real_jid, stanza);
486 log("debug", "session %s is changing from occupant %s to %s", real_jid, orig_occupant.nick, dest_occupant.nick);
487 local generated_unavail = st.presence {from = orig_occupant.nick, to = real_jid, type = "unavailable"};
488 orig_occupant:set_session(real_jid, generated_unavail);
489 dest_nick = select(3, jid_split(dest_occupant.nick));
490 if not is_first_dest_session then -- User is swapping into another pre-existing session
491 log("debug", "session %s is swapping into multisession %s, showing it leave.", real_jid, dest_occupant.nick);
492 -- Show the other session leaving
493 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
494 :tag("status"):text("you are joining pre-existing session " .. dest_nick):up();
495 add_item(x, self:get_affiliation(bare_jid), "none");
496 local pr = st.presence{from = dest_occupant.nick, to = real_jid, type = "unavailable"}
498 self:route_stanza(pr);
500 if is_first_dest_session and is_last_orig_session then -- Normal nick change
501 log("debug", "no sessions in %s left; publically marking as nick change", orig_occupant.nick);
502 orig_x:tag("status", {code = "303";}):up();
503 else -- The session itself always needs to see a nick change
504 -- don't want to get our old nick's available presence,
505 -- so remove our session from there, and manually generate an unavailable
506 orig_occupant:remove_session(real_jid);
507 log("debug", "generating nick change for %s", real_jid);
508 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
509 -- self:build_item_list(orig_occupant, x, false, dest_nick); -- COMPAT: clients get confused if they see other items besides their own
510 add_item(x, self:get_affiliation(bare_jid), orig_occupant.role, real_jid, dest_nick);
511 x:tag("status", {code = "303";}):up();
512 x:tag("status", {code = "110";}):up();
513 self:route_stanza(generated_unavail:add_child(x));
514 dest_nick = nil; -- set dest_nick to nil; so general populance doesn't see it for whole orig_occupant
517 self:save_occupant(orig_occupant);
518 self:publicise_occupant_status(orig_occupant, orig_x, dest_nick);
520 if is_last_orig_session then
521 module:fire_event("muc-occupant-left", {room = self; nick = orig_occupant.nick;});
525 if dest_occupant ~= nil then
526 dest_occupant:set_session(real_jid, stanza);
527 local dest_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
529 dest_x:tag("status", {code = "201"}):up();
531 if orig_occupant == nil and self:get_whois() == "anyone" then
532 dest_x:tag("status", {code = "100"}):up();
534 self:save_occupant(dest_occupant);
535 self:publicise_occupant_status(dest_occupant, dest_x);
537 if orig_occupant ~= nil and orig_occupant ~= dest_occupant and not is_last_orig_session then -- If user is swapping and wasn't last original session
538 log("debug", "session %s split nicks; showing %s rejoining", real_jid, orig_occupant.nick);
539 -- Show the original nick joining again
540 local pr = st.clone(orig_occupant:get_presence());
541 pr.attr.to = real_jid;
542 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
543 self:build_item_list(orig_occupant, x, false);
544 -- TODO: new status code to inform client this was the multi-session it left?
546 self:route_stanza(pr);
549 if orig_occupant == nil and is_first_dest_session then
550 module:fire_event("muc-occupant-joined", {room = self; nick = dest_occupant.nick; stanza = stanza;});
553 elseif type ~= 'result' then -- bad type
554 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
555 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
561 function room_mt:handle_iq_to_occupant(origin, stanza)
562 local from, to = stanza.attr.from, stanza.attr.to;
563 local type = stanza.attr.type;
564 local id = stanza.attr.id;
565 local occupant = self:get_occupant_by_nick(to);
566 if (type == "error" or type == "result") then
567 do -- deconstruct_stanza_id
568 if not occupant then return nil; end
569 local from_jid, id, to_jid_hash = (base64.decode(stanza.attr.id) or ""):match("^(.+)%z(.*)%z(.+)$");
570 if not(from == from_jid or from == jid_bare(from_jid)) then return nil; end
571 local from_occupant_jid = self:get_occupant_jid(from_jid);
572 if from_occupant_jid == nil then return nil; end
574 for to_jid in occupant:each_session() do
575 if md5(to_jid) == to_jid_hash then
576 session_jid = to_jid;
580 if session_jid == nil then return nil; end
581 stanza.attr.from, stanza.attr.to, stanza.attr.id = from_jid, session_jid, id;
583 log("debug", "%s sent private iq stanza to %s (%s)", from, to, stanza.attr.to);
584 self:route_stanza(stanza);
585 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
587 else -- Type is "get" or "set"
588 local current_nick = self:get_occupant_jid(from);
589 if not current_nick then
590 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
593 if not occupant then -- recipient not in room
594 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
597 do -- construct_stanza_id
598 stanza.attr.id = base64.encode(occupant.jid.."\0"..stanza.attr.id.."\0"..md5(from));
600 stanza.attr.from, stanza.attr.to = current_nick, occupant.jid;
601 log("debug", "%s sent private iq stanza to %s (%s)", from, to, occupant.jid);
602 if stanza.tags[1].attr.xmlns == 'vcard-temp' then
603 stanza.attr.to = jid_bare(stanza.attr.to);
605 self:route_stanza(stanza);
606 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
611 function room_mt:handle_message_to_occupant(origin, stanza)
612 local from, to = stanza.attr.from, stanza.attr.to;
613 local current_nick = self:get_occupant_jid(from);
614 local type = stanza.attr.type;
615 if not current_nick then -- not in room
616 if type ~= "error" then
617 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
621 if type == "groupchat" then -- groupchat messages not allowed in PM
622 origin.send(st.error_reply(stanza, "modify", "bad-request"));
624 elseif type == "error" and is_kickable_error(stanza) then
625 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
626 return self:handle_kickable(origin, stanza); -- send unavailable
629 local o_data = self:get_occupant_by_nick(to);
631 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
634 log("debug", "%s sent private message stanza to %s (%s)", from, to, o_data.jid);
635 stanza:tag("x", { xmlns = "http://jabber.org/protocol/muc#user" }):up();
636 stanza.attr.from = current_nick;
637 self:route_to_occupant(o_data, stanza)
638 -- TODO: Remove x tag?
639 stanza.attr.from = from;
643 function room_mt:send_form(origin, stanza)
644 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
645 :add_child(self:get_form_layout(stanza.attr.from):form())
649 function room_mt:get_form_layout(actor)
650 local form = dataform.new({
651 title = "Configuration for "..self.jid,
652 instructions = "Complete and submit this form to configure the room.",
656 value = 'http://jabber.org/protocol/muc#roomconfig'
659 return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
661 module:hook("muc-config-form", function(event)
662 table.insert(event.form, {
663 name = 'muc#roomconfig_publicroom',
665 label = 'Make Room Publicly Searchable?',
666 value = not event.room:get_hidden()
669 module:hook("muc-config-form", function(event)
670 table.insert(event.form, {
671 name = 'muc#roomconfig_changesubject',
673 label = 'Allow Occupants to Change Subject?',
674 value = event.room:get_changesubject()
677 module:hook("muc-config-form", function(event)
678 table.insert(event.form, {
679 name = 'muc#roomconfig_moderatedroom',
681 label = 'Make Room Moderated?',
682 value = event.room:get_moderated()
686 function room_mt:process_form(origin, stanza)
687 local form = stanza.tags[1]:get_child("x", "jabber:x:data");
688 if form.attr.type == "cancel" then
689 origin.send(st.reply(stanza));
690 elseif form.attr.type == "submit" then
691 local fields = self:get_form_layout(stanza.attr.from):data(form);
692 if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then
693 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration"));
697 local event = {room = self; origin = origin; stanza = stanza; fields = fields; status_codes = {};};
698 function event.update_option(name, field, allowed)
699 local new = fields[field];
700 if new == nil then return; end
701 if allowed and not allowed[new] then return; end
702 if new == self["get_"..name](self) then return; end
703 event.status_codes["104"] = true;
704 self["set_"..name](self, new);
707 module:fire_event("muc-config-submitted", event);
709 if self.save then self:save(true); end
710 origin.send(st.reply(stanza));
712 if next(event.status_codes) then
713 local msg = st.message({type='groupchat', from=self.jid})
714 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
715 for code in pairs(event.status_codes) do
716 msg:tag("status", {code = code;}):up();
719 self:broadcast_message(msg);
722 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form"));
726 module:hook("muc-config-submitted", function(event)
727 event.update_option("moderated", "muc#roomconfig_moderatedroom");
729 module:hook("muc-config-submitted", function(event)
730 event.update_option("public", "muc#roomconfig_publicroom");
732 module:hook("muc-config-submitted", function(event)
733 event.update_option("changesubject", "muc#roomconfig_changesubject");
736 -- Removes everyone from the room
737 function room_mt:clear(x)
738 x = x or st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
739 local occupants_updated = {};
740 for nick, occupant in self:each_occupant() do
742 self:save_occupant(occupant);
743 occupants_updated[occupant] = true;
745 for occupant in pairs(occupants_updated) do
746 self:publicise_occupant_status(occupant, x);
747 module:fire_event("muc-occupant-left", { room = self; nick = occupant.nick; });
751 function room_mt:destroy(newjid, reason, password)
752 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
753 :tag("item", { affiliation='none', role='none' }):up()
754 :tag("destroy", {jid=newjid});
755 if reason then x:tag("reason"):text(reason):up(); end
756 if password then x:tag("password"):text(password):up(); end
759 module:fire_event("muc-room-destroyed", { room = self });
762 function room_mt:handle_disco_info_get_query(origin, stanza)
763 origin.send(self:get_disco_info(stanza));
767 function room_mt:handle_disco_items_get_query(origin, stanza)
768 origin.send(self:get_disco_items(stanza));
772 function room_mt:handle_admin_query_set_command(origin, stanza)
773 local item = stanza.tags[1].tags[1];
774 if item.attr.jid then -- Validate provided JID
775 item.attr.jid = jid_prep(item.attr.jid);
776 if not item.attr.jid then
777 origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
781 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
782 local occupant = self:get_occupant_by_nick(self.jid.."/"..item.attr.nick);
783 if occupant then item.attr.jid = occupant.jid; end
784 elseif not item.attr.nick and item.attr.jid then
785 local nick = self:get_occupant_jid(item.attr.jid);
786 if nick then item.attr.nick = select(3, jid_split(nick)); end
788 local actor = stanza.attr.from;
789 local reason = item:get_child_text("reason");
790 local success, errtype, err
791 if item.attr.affiliation and item.attr.jid and not item.attr.role then
792 success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, reason);
793 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
794 success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, reason);
796 success, errtype, err = nil, "cancel", "bad-request";
798 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
799 origin.send(st.reply(stanza));
803 function room_mt:handle_admin_query_get_command(origin, stanza)
804 local actor = stanza.attr.from;
805 local affiliation = self:get_affiliation(actor);
806 local item = stanza.tags[1].tags[1];
807 local _aff = item.attr.affiliation;
808 local _rol = item.attr.role;
809 if _aff and not _rol then
810 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
811 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
812 for jid, affiliation in pairs(self._affiliations) do
813 if affiliation == _aff then
814 reply:tag("item", {affiliation = _aff, jid = jid}):up();
820 origin.send(st.error_reply(stanza, "auth", "forbidden"));
823 elseif _rol and not _aff then
824 local role = self:get_role(self:get_occupant_jid(actor)) or self:get_default_role(affiliation);
825 if valid_roles[role or "none"] >= valid_roles.moderator then
826 if _rol == "none" then _rol = nil; end
827 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
828 -- TODO: whois check here? (though fully anonymous rooms are not supported)
829 for occupant_jid, occupant in self:each_occupant() do
830 if occupant.role == _rol then
831 local nick = select(3,jid_split(occupant_jid));
832 self:build_item_list(occupant, reply, false, nick);
835 origin.send(reply:up());
838 origin.send(st.error_reply(stanza, "auth", "forbidden"));
842 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
847 function room_mt:handle_owner_query_get_to_room(origin, stanza)
848 if self:get_affiliation(stanza.attr.from) ~= "owner" then
849 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
853 self:send_form(origin, stanza);
856 function room_mt:handle_owner_query_set_to_room(origin, stanza)
857 if self:get_affiliation(stanza.attr.from) ~= "owner" then
858 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
862 local child = stanza.tags[1].tags[1];
864 origin.send(st.error_reply(stanza, "modify", "bad-request"));
866 elseif child.name == "destroy" then
867 local newjid = child.attr.jid;
868 local reason = child:get_child_text("reason");
869 local password = child:get_child_text("password");
870 self:destroy(newjid, reason, password);
871 origin.send(st.reply(stanza));
873 elseif child.name == "x" and child.attr.xmlns == "jabber:x:data" then
874 return self:process_form(origin, stanza);
876 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
881 function room_mt:handle_groupchat_to_room(origin, stanza)
882 local from = stanza.attr.from;
883 local occupant = self:get_occupant_by_real_jid(from);
884 if not occupant then -- not in room
885 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
887 elseif occupant.role == "visitor" then
888 origin.send(st.error_reply(stanza, "auth", "forbidden"));
891 local from = stanza.attr.from;
892 stanza.attr.from = occupant.nick;
893 local subject = stanza:get_child_text("subject");
895 if occupant.role == "moderator" or
896 ( self:get_changesubject() and occupant.role == "participant" ) then -- and participant
897 self:set_subject(occupant.nick, subject);
899 stanza.attr.from = from;
900 origin.send(st.error_reply(stanza, "auth", "forbidden"));
903 self:broadcast_message(stanza);
905 stanza.attr.from = from;
910 -- hack - some buggy clients send presence updates to the room rather than their nick
911 function room_mt:handle_presence_to_room(origin, stanza)
912 local current_nick = self:get_occupant_jid(stanza.attr.from);
915 local to = stanza.attr.to;
916 stanza.attr.to = current_nick;
917 handled = self:handle_presence_to_occupant(origin, stanza);
923 -- Need visitor role or higher to invite
924 module:hook("muc-pre-invite", function(event)
925 local room, stanza = event.room, event.stanza;
926 local _from, _to = stanza.attr.from, stanza.attr.to;
927 local inviter = room:get_occupant_by_real_jid(_from);
928 local role = inviter and inviter.role or room:get_default_role(room:get_affiliation(_from));
929 if valid_roles[role or "none"] <= valid_roles.visitor then
930 event.origin.send(st.error_reply(stanza, "auth", "forbidden"));
935 function room_mt:handle_mediated_invite(origin, stanza)
936 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
937 local invitee = jid_prep(payload.attr.to);
939 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
941 elseif not module:fire_event("muc-pre-invite", {room = self, origin = origin, stanza = stanza}) then
944 local invite = st.message({from = self.jid, to = invitee, id = stanza.attr.id})
945 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
946 :tag('invite', {from = stanza.attr.from;})
947 :tag('reason'):text(payload:get_child_text("reason")):up()
950 if not module:fire_event("muc-invite", {room = self, stanza = invite, origin = origin, incoming = stanza}) then
951 self:route_stanza(invite);
956 -- COMPAT: Some older clients expect this
957 module:hook("muc-invite", function(event)
958 local room, stanza = event.room, event.stanza;
959 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
960 local reason = invite:get_child_text("reason");
961 stanza:tag('x', {xmlns = "jabber:x:conference"; jid = room.jid;})
966 -- Add a plain message for clients which don't support invites
967 module:hook("muc-invite", function(event)
968 local room, stanza = event.room, event.stanza;
969 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
970 local reason = invite:get_child_text("reason") or "";
972 :text(invite.attr.from.." invited you to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
976 function room_mt:handle_mediated_decline(origin, stanza)
977 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
978 local declinee = jid_prep(payload.attr.to);
980 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
982 elseif not module:fire_event("muc-pre-decline", {room = self, origin = origin, stanza = stanza}) then
985 local decline = st.message({from = self.jid, to = declinee, id = stanza.attr.id})
986 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
987 :tag("decline", {from = stanza.attr.from})
988 :tag("reason"):text(payload:get_child_text("reason")):up()
991 if not module:fire_event("muc-decline", {room = self, stanza = decline, origin = origin, incoming = stanza}) then
992 local occupant = self:get_occupant_by_real_jid(decline.attr.to);
994 self:route_to_occupant(occupant, decline);
996 self:route_stanza(decline);
1002 -- Add a plain message for clients which don't support declines
1003 module:hook("muc-decline", function(event)
1004 local room, stanza = event.room, event.stanza;
1005 local decline = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
1006 local reason = decline:get_child_text("reason") or "";
1008 :text(decline.attr.from.." declined your invite to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
1012 function room_mt:handle_message_to_room(origin, stanza)
1013 local type = stanza.attr.type;
1014 if type == "groupchat" then
1015 return self:handle_groupchat_to_room(origin, stanza)
1016 elseif type == "error" and is_kickable_error(stanza) then
1017 return self:handle_kickable(origin, stanza)
1018 elseif type == nil then
1019 local x = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1021 local payload = x.tags[1];
1022 if payload == nil then
1024 elseif payload.name == "invite" and payload.attr.to then
1025 return self:handle_mediated_invite(origin, stanza)
1026 elseif payload.name == "decline" and payload.attr.to then
1027 return self:handle_mediated_decline(origin, stanza)
1029 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
1035 function room_mt:route_stanza(stanza)
1036 module:send(stanza);
1039 function room_mt:get_affiliation(jid)
1040 local node, host, resource = jid_split(jid);
1041 local bare = node and node.."@"..host or host;
1042 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
1043 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
1047 function room_mt:set_affiliation(actor, jid, affiliation, reason)
1048 if not actor then return nil, "modify", "not-acceptable"; end;
1050 jid = jid_bare(jid);
1052 if valid_affiliations[affiliation or "none"] == nil then
1053 return nil, "modify", "not-acceptable";
1055 affiliation = affiliation ~= "none" and affiliation or nil; -- coerces `affiliation == false` to `nil`
1057 local target_affiliation = self._affiliations[jid]; -- Raw; don't want to check against host
1058 local is_downgrade = valid_affiliations[target_affiliation or "none"] > valid_affiliations[affiliation or "none"];
1060 if actor ~= true then
1061 local actor_bare = jid_bare(actor);
1062 local actor_affiliation = self._affiliations[actor_bare];
1063 if actor_affiliation == "owner" then
1064 if actor_bare == jid then -- self change
1065 -- need at least one owner
1066 local is_last = true;
1067 for j, aff in pairs(self._affiliations) do if j ~= jid and aff == "owner" then is_last = false; break; end end
1069 return nil, "cancel", "conflict";
1072 -- owners can do anything else
1073 elseif affiliation == "owner" or affiliation == "admin"
1074 or actor_affiliation ~= "admin"
1075 or target_affiliation == "owner" or target_affiliation == "admin" then
1076 -- Can't demote owners or other admins
1077 return nil, "cancel", "not-allowed";
1081 -- Set in 'database'
1082 self._affiliations[jid] = affiliation;
1085 local role = self:get_default_role(affiliation);
1086 local role_rank = valid_roles[role or "none"];
1087 local occupants_updated = {}; -- Filled with old roles
1088 for nick, occupant in self:each_occupant() do
1089 if occupant.bare_jid == jid then
1090 -- need to publcize in all cases; as affiliation in <item/> has changed.
1091 occupants_updated[occupant] = occupant.role;
1092 if occupant.role ~= role and (
1094 valid_roles[occupant.role or "none"] < role_rank -- upgrade
1096 occupant.role = role;
1097 self:save_occupant(occupant);
1102 -- Tell the room of the new occupant affiliations+roles
1103 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1104 if not role then -- getting kicked
1105 if affiliation == "outcast" then
1106 x:tag("status", {code="301"}):up(); -- banned
1108 x:tag("status", {code="321"}):up(); -- affiliation change
1111 local is_semi_anonymous = self:get_whois() == "moderators";
1112 for occupant, old_role in pairs(occupants_updated) do
1113 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1114 if is_semi_anonymous and
1115 (old_role == "moderator" and occupant.role ~= "moderator") or
1116 (old_role ~= "moderator" and occupant.role == "moderator") then -- Has gained or lost moderator status
1117 -- Send everyone else's presences (as jid visibility has changed)
1118 for real_jid in occupant:each_session() do
1119 self:send_occupant_list(real_jid, function(occupant_jid, occupant)
1120 return occupant.bare_jid ~= jid;
1126 if self.save then self:save(); end
1130 function room_mt:get_role(nick)
1131 local occupant = self:get_occupant_by_nick(nick);
1132 return occupant and occupant.role or nil;
1135 function room_mt:set_role(actor, occupant_jid, role, reason)
1136 if not actor then return nil, "modify", "not-acceptable"; end
1138 local occupant = self:get_occupant_by_nick(occupant_jid);
1139 if not occupant then return nil, "modify", "not-acceptable"; end
1141 if valid_roles[role or "none"] == nil then
1142 return nil, "modify", "not-acceptable";
1144 role = role ~= "none" and role or nil; -- coerces `role == false` to `nil`
1146 if actor ~= true then
1147 -- Can't do anything to other owners or admins
1148 local occupant_affiliation = self:get_affiliation(occupant.bare_jid);
1149 if occupant_affiliation == "owner" and occupant_affiliation == "admin" then
1150 return nil, "cancel", "not-allowed";
1153 -- If you are trying to give or take moderator role you need to be an owner or admin
1154 if occupant.role == "moderator" or role == "moderator" then
1155 local actor_affiliation = self:get_affiliation(actor);
1156 if actor_affiliation ~= "owner" and actor_affiliation ~= "admin" then
1157 return nil, "cancel", "not-allowed";
1161 -- Need to be in the room and a moderator
1162 local actor_occupant = self:get_occupant_by_real_jid(actor);
1163 if not actor_occupant or actor_occupant.role ~= "moderator" then
1164 return nil, "cancel", "not-allowed";
1168 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1170 x:tag("status", {code = "307"}):up();
1172 occupant.role = role;
1173 self:save_occupant(occupant);
1174 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1178 local name = module:require "muc/name";
1179 room_mt.get_name = name.get;
1180 room_mt.set_name = name.set;
1182 local description = module:require "muc/description";
1183 room_mt.get_description = description.get;
1184 room_mt.set_description = description.set;
1186 local password = module:require "muc/password";
1187 room_mt.get_password = password.get;
1188 room_mt.set_password = password.set;
1190 local whois = module:require "muc/whois";
1191 room_mt.get_whois = whois.get;
1192 room_mt.set_whois = whois.set;
1194 local members_only = module:require "muc/members_only";
1195 room_mt.get_members_only = members_only.get;
1196 room_mt.set_members_only = members_only.set;
1198 local persistent = module:require "muc/persistent";
1199 room_mt.get_persistent = persistent.get;
1200 room_mt.set_persistent = persistent.set;
1202 local history = module:require "muc/history";
1203 room_mt.send_history = history.send;
1204 room_mt.get_historylength = history.get_length;
1205 room_mt.set_historylength = history.set_length;
1207 local _M = {}; -- module "muc"
1209 _M.set_max_history_length = history.set_max_length;
1211 function _M.new_room(jid, config)
1212 return setmetatable({
1222 _M.room_mt = room_mt;