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 jid_join = require "util.jid".join;
21 local st = require "util.stanza";
22 local log = require "util.logger".init("mod_muc");
23 local base64 = require "util.encodings".base64;
24 local md5 = require "util.hashes".md5;
26 local occupant_lib = module:require "muc/occupant"
27 local muc_util = module:require "muc/util";
28 local is_kickable_error = muc_util.is_kickable_error;
29 local valid_roles, valid_affiliations = muc_util.valid_roles, muc_util.valid_affiliations;
32 room_mt.__index = room_mt;
34 function room_mt:__tostring()
35 return "MUC room ("..self.jid..")";
38 function room_mt:get_occupant_jid(real_jid)
39 return self._jid_nick[real_jid]
42 function room_mt:get_default_role(affiliation)
43 local role = module:fire_event("muc-get-default-role", {
45 affiliation = affiliation;
46 affiliation_rank = valid_affiliations[affiliation or "none"];
48 return role, valid_roles[role or "none"];
50 module:hook("muc-get-default-role", function(event)
51 if event.affiliation_rank >= valid_affiliations.admin then
53 elseif event.affiliation_rank >= valid_affiliations.none then
58 --- Occupant functions
59 function room_mt:new_occupant(bare_real_jid, nick)
60 local occupant = occupant_lib.new(bare_real_jid, nick);
61 local affiliation = self:get_affiliation(bare_real_jid);
62 occupant.role = self:get_default_role(affiliation);
66 function room_mt:get_occupant_by_nick(nick)
67 local occupant = self._occupants[nick];
68 if occupant == nil then return nil end
69 return occupant_lib.copy(occupant);
73 local function next_copied_occupant(occupants, occupant_jid)
74 local next_occupant_jid, raw_occupant = next(occupants, occupant_jid);
75 if next_occupant_jid == nil then return nil end
76 return next_occupant_jid, occupant_lib.copy(raw_occupant);
78 function room_mt:each_occupant(read_only)
79 return next_copied_occupant, self._occupants, nil;
83 function room_mt:has_occupant()
84 return next(self._occupants, nil) ~= 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 old_occupant:each_session() do
101 self._jid_nick[real_jid] = nil;
105 local has_live_session = false
106 if occupant.role ~= nil then
107 for real_jid, presence in occupant:each_session() do
108 if presence.attr.type == nil then
109 has_live_session = true
110 self._jid_nick[real_jid] = occupant.nick;
113 if not has_live_session then
114 -- Has no live sessions left; they have left the room.
118 if not has_live_session then
121 self._occupants[id] = occupant
124 function room_mt:route_to_occupant(occupant, stanza)
125 local to = stanza.attr.to;
126 for jid, pr in occupant:each_session() do
127 stanza.attr.to = jid;
128 self:route_stanza(stanza);
133 -- actor is the attribute table
134 local function add_item(x, affiliation, role, jid, nick, actor_nick, actor_jid, reason)
135 x:tag("item", {affiliation = affiliation; role = role; jid = jid; nick = nick;})
136 if actor_nick or actor_jid then
137 x:tag("actor", {nick = actor_nick; jid = actor_jid;}):up()
140 x:tag("reason"):text(reason):up()
146 -- actor is (real) jid
147 function room_mt:build_item_list(occupant, x, is_anonymous, nick, actor_nick, actor_jid, reason)
148 local affiliation = self:get_affiliation(occupant.bare_jid) or "none";
149 local role = occupant.role or "none";
151 add_item(x, affiliation, role, nil, nick, actor_nick, actor_jid, reason);
153 for real_jid, session in occupant:each_session() do
154 add_item(x, affiliation, role, real_jid, nick, actor_nick, actor_jid, reason);
160 function room_mt:broadcast_message(stanza)
161 if module:fire_event("muc-broadcast-message", {room = self, stanza = stanza}) then
164 self:broadcast(stanza);
168 -- Broadcast a stanza to all occupants in the room.
169 -- optionally checks conditional called with (nick, occupant)
170 function room_mt:broadcast(stanza, cond_func)
171 for nick, occupant in self:each_occupant() do
172 if cond_func == nil or cond_func(nick, occupant) then
173 self:route_to_occupant(occupant, stanza)
178 local function can_see_real_jids(whois, occupant)
179 if whois == "anyone" then
181 elseif whois == "moderators" then
182 return valid_roles[occupant.role or "none"] >= valid_roles.moderator;
186 -- Broadcasts an occupant's presence to the whole room
187 -- Takes the x element that goes into the stanzas
188 function room_mt:publicise_occupant_status(occupant, base_x, nick, actor, reason)
189 -- Build real jid and (optionally) occupant jid template presences
190 local base_presence do
191 -- Try to use main jid's presence
192 local pr = occupant:get_presence();
193 if pr and (pr.attr.type ~= "unavailable" or occupant.role == nil) then
194 base_presence = st.clone(pr);
195 else -- user is leaving but didn't send a leave presence. make one for them
196 base_presence = st.presence {from = occupant.nick; type = "unavailable";};
200 -- Fire event (before full_p and anon_p are created)
202 room = self; stanza = base_presence; x = base_x;
203 occupant = occupant; nick = nick; actor = actor;
206 module:fire_event("muc-broadcast-presence", event);
208 -- Allow muc-broadcast-presence listeners to change things
211 reason = event.reason;
213 local whois = self:get_whois();
217 actor_nick = select(3, jid_split(self:get_occupant_jid(actor)));
220 local full_p, full_x;
221 local function get_full_p()
222 if full_p == nil then
223 full_x = st.clone(base_x);
224 self:build_item_list(occupant, full_x, false, nick, actor_nick, actor, reason);
225 full_p = st.clone(base_presence):add_child(full_x);
227 return full_p, full_x;
230 local anon_p, anon_x;
231 local function get_anon_p()
232 if anon_p == nil then
233 anon_x = st.clone(base_x);
234 self:build_item_list(occupant, anon_x, true, nick, actor_nick, nil, reason);
235 anon_p = st.clone(base_presence):add_child(anon_x);
237 return anon_p, anon_x;
240 local self_p, self_x;
241 if can_see_real_jids(whois, occupant) then
242 self_p, self_x = get_full_p();
244 -- Can always see your own full jids
245 -- But not allowed to see actor's
246 self_x = st.clone(base_x);
247 self:build_item_list(occupant, self_x, false, nick, actor_nick, nil, reason);
248 self_p = st.clone(base_presence):add_child(self_x);
252 for nick, n_occupant in self:each_occupant() do
253 if nick ~= occupant.nick then
255 if can_see_real_jids(whois, n_occupant) then
257 elseif occupant.bare_jid == n_occupant.bare_jid then
262 self:route_to_occupant(n_occupant, pr);
266 -- Presences for occupant itself
267 self_x:tag("status", {code = "110";}):up();
268 if occupant.role == nil then
269 -- They get an unavailable
270 self:route_to_occupant(occupant, self_p);
272 -- use their own presences as templates
273 for full_jid, pr in occupant:each_session() do
275 pr.attr.to = full_jid;
276 pr:add_child(self_x);
277 self:route_stanza(pr);
282 function room_mt:send_occupant_list(to, filter)
283 local to_bare = jid_bare(to);
284 local is_anonymous = false;
285 local whois = self:get_whois();
286 if whois ~= "anyone" then
287 local affiliation = self:get_affiliation(to);
288 if affiliation ~= "admin" and affiliation ~= "owner" then
289 local occupant = self:get_occupant_by_real_jid(to);
290 if not (occupant and can_see_real_jids(whois, occupant)) then
295 for occupant_jid, occupant in self:each_occupant() do
296 if filter == nil or filter(occupant_jid, occupant) then
297 local x = st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
298 self:build_item_list(occupant, x, is_anonymous and to_bare ~= occupant.bare_jid); -- can always see your own jids
299 local pres = st.clone(occupant:get_presence());
302 self:route_stanza(pres);
307 function room_mt:get_disco_info(stanza)
308 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#info");
309 local form = dataform.new {
310 { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" };
312 module:fire_event("muc-disco#info", {room = self; reply = reply; form = form;});
313 reply:add_child(form:form(nil, "result"));
316 module:hook("muc-disco#info", function(event)
317 event.reply:tag("feature", {var = "http://jabber.org/protocol/muc"}):up();
319 module:hook("muc-disco#info", function(event)
320 local count = iterators.count(event.room:each_occupant());
321 table.insert(event.form, { name = "muc#roominfo_occupants", label = "Number of occupants", value = tostring(count) });
324 function room_mt:get_disco_items(stanza)
325 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
326 for room_jid in self:each_occupant() do
327 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
332 function room_mt:handle_kickable(origin, stanza)
333 local real_jid = stanza.attr.from;
334 local occupant = self:get_occupant_by_real_jid(real_jid);
335 if occupant == nil then return nil; end
336 local type, condition, text = stanza:get_error();
337 local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
339 error_message = error_message..": "..text;
341 occupant:set_session(real_jid, st.presence({type="unavailable"})
342 :tag('status'):text(error_message));
343 self:save_occupant(occupant);
344 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
345 :tag("status", {code = "307"})
346 self:publicise_occupant_status(occupant, x);
347 if occupant.jid == real_jid then -- Was last session
348 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
353 -- Give the room creator owner affiliation
354 module:hook("muc-room-pre-create", function(event)
355 event.room:set_affiliation(true, jid_bare(event.stanza.attr.from), "owner");
358 -- check if user is banned
359 module:hook("muc-occupant-pre-join", function(event)
360 local room, stanza = event.room, event.stanza;
361 local affiliation = room:get_affiliation(stanza.attr.from);
362 if affiliation == "outcast" then
363 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
364 reply.tags[1].attr.code = "403";
365 event.origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
370 function room_mt:handle_presence_to_occupant(origin, stanza)
371 local type = stanza.attr.type;
372 if type == "error" then -- error, kick em out!
373 return self:handle_kickable(origin, stanza)
374 elseif type == nil or type == "unavailable" then
375 local real_jid = stanza.attr.from;
376 local bare_jid = jid_bare(real_jid);
377 local orig_occupant, dest_occupant;
378 local is_new_room = next(self._affiliations) == nil;
380 if type == "unavailable" then return true; end -- Unavailable from someone not in the room
381 if module:fire_event("muc-room-pre-create", {
385 }) then return true; end
387 orig_occupant = self:get_occupant_by_real_jid(real_jid);
388 if type == "unavailable" and orig_occupant == nil then return true; end -- Unavailable from someone not in the room
390 local is_first_dest_session;
391 if type == "unavailable" then
392 -- dest_occupant = nil
393 elseif orig_occupant and orig_occupant.nick == stanza.attr.to then -- Just a presence update
394 log("debug", "presence update for %s from session %s", orig_occupant.nick, real_jid);
395 dest_occupant = orig_occupant;
397 local dest_jid = stanza.attr.to;
398 dest_occupant = self:get_occupant_by_nick(dest_jid);
399 if dest_occupant == nil then
400 log("debug", "no occupant found for %s; creating new occupant object for %s", dest_jid, real_jid);
401 is_first_dest_session = true;
402 dest_occupant = self:new_occupant(bare_jid, dest_jid);
404 is_first_dest_session = false;
407 local is_last_orig_session;
408 if orig_occupant ~= nil then
409 -- Is there are least 2 sessions?
410 local iter, ob, last = orig_occupant:each_session();
411 is_last_orig_session = iter(ob, iter(ob, last)) == nil;
414 local event, event_name = {
418 is_first_session = is_first_dest_session;
419 is_last_session = is_last_orig_session;
421 if orig_occupant == nil then
422 event_name = "muc-occupant-pre-join";
423 event.is_new_room = is_new_room;
424 event.occupant = dest_occupant;
425 elseif dest_occupant == nil then
426 event_name = "muc-occupant-pre-leave";
427 event.occupant = orig_occupant;
429 event_name = "muc-occupant-pre-change";
430 event.orig_occupant = orig_occupant;
431 event.dest_occupant = dest_occupant;
433 if module:fire_event(event_name, event) then return true; end
435 -- Check for nick conflicts
436 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
437 log("debug", "%s couldn't join due to nick conflict: %s", real_jid, dest_occupant.nick);
438 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
439 reply.tags[1].attr.code = "409";
440 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
444 -- Send presence stanza about original occupant
445 if orig_occupant ~= nil and orig_occupant ~= dest_occupant then
446 local orig_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
448 if dest_occupant == nil then -- Session is leaving
449 log("debug", "session %s is leaving occupant %s", real_jid, orig_occupant.nick);
450 if is_last_orig_session then
451 orig_occupant.role = nil;
453 orig_occupant:set_session(real_jid, stanza);
455 log("debug", "session %s is changing from occupant %s to %s", real_jid, orig_occupant.nick, dest_occupant.nick);
456 local generated_unavail = st.presence {from = orig_occupant.nick, to = real_jid, type = "unavailable"};
457 orig_occupant:set_session(real_jid, generated_unavail);
458 dest_nick = select(3, jid_split(dest_occupant.nick));
459 if not is_first_dest_session then -- User is swapping into another pre-existing session
460 log("debug", "session %s is swapping into multisession %s, showing it leave.", real_jid, dest_occupant.nick);
461 -- Show the other session leaving
462 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
463 :tag("status"):text("you are joining pre-existing session " .. dest_nick):up();
464 add_item(x, self:get_affiliation(bare_jid), "none");
465 local pr = st.presence{from = dest_occupant.nick, to = real_jid, type = "unavailable"}
467 self:route_stanza(pr);
469 if is_first_dest_session and is_last_orig_session then -- Normal nick change
470 log("debug", "no sessions in %s left; publically marking as nick change", orig_occupant.nick);
471 orig_x:tag("status", {code = "303";}):up();
472 else -- The session itself always needs to see a nick change
473 -- don't want to get our old nick's available presence,
474 -- so remove our session from there, and manually generate an unavailable
475 orig_occupant:remove_session(real_jid);
476 log("debug", "generating nick change for %s", real_jid);
477 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
478 -- self:build_item_list(orig_occupant, x, false, dest_nick); -- COMPAT: clients get confused if they see other items besides their own
479 add_item(x, self:get_affiliation(bare_jid), orig_occupant.role, real_jid, dest_nick);
480 x:tag("status", {code = "303";}):up();
481 x:tag("status", {code = "110";}):up();
482 self:route_stanza(generated_unavail:add_child(x));
483 dest_nick = nil; -- set dest_nick to nil; so general populance doesn't see it for whole orig_occupant
486 self:save_occupant(orig_occupant);
487 self:publicise_occupant_status(orig_occupant, orig_x, dest_nick);
489 if is_last_orig_session then
490 module:fire_event("muc-occupant-left", {room = self; nick = orig_occupant.nick; occupant = orig_occupant;});
494 if dest_occupant ~= nil then
495 dest_occupant:set_session(real_jid, stanza);
496 local dest_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
498 dest_x:tag("status", {code = "201"}):up();
500 if orig_occupant == nil and self:get_whois() == "anyone" then
501 dest_x:tag("status", {code = "100"}):up();
503 self:save_occupant(dest_occupant);
505 if orig_occupant == nil then
506 -- Send occupant list to newly joined user
507 self:send_occupant_list(real_jid, function(nick, occupant)
508 -- Don't include self
509 return occupant:get_presence(real_jid) == nil;
512 self:publicise_occupant_status(dest_occupant, dest_x);
514 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
515 log("debug", "session %s split nicks; showing %s rejoining", real_jid, orig_occupant.nick);
516 -- Show the original nick joining again
517 local pr = st.clone(orig_occupant:get_presence());
518 pr.attr.to = real_jid;
519 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
520 self:build_item_list(orig_occupant, x, false);
521 -- TODO: new status code to inform client this was the multi-session it left?
523 self:route_stanza(pr);
526 if orig_occupant == nil then
527 if is_first_dest_session then
528 module:fire_event("muc-occupant-joined", {room = self; nick = dest_occupant.nick; occupant = dest_occupant;});
530 module:fire_event("muc-occupant-session-new", {room = self; nick = dest_occupant.nick; occupant = dest_occupant; stanza = stanza; jid = real_jid;});
533 elseif type ~= 'result' then -- bad type
534 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
535 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
541 function room_mt:handle_iq_to_occupant(origin, stanza)
542 local from, to = stanza.attr.from, stanza.attr.to;
543 local type = stanza.attr.type;
544 local id = stanza.attr.id;
545 local occupant = self:get_occupant_by_nick(to);
546 if (type == "error" or type == "result") then
547 do -- deconstruct_stanza_id
548 if not occupant then return nil; end
549 local from_jid, id, to_jid_hash = (base64.decode(stanza.attr.id) or ""):match("^(%Z+)%z(%Z*)%z(.+)$");
550 if not(from == from_jid or from == jid_bare(from_jid)) then return nil; end
551 local from_occupant_jid = self:get_occupant_jid(from_jid);
552 if from_occupant_jid == nil then return nil; end
554 for to_jid in occupant:each_session() do
555 if md5(to_jid) == to_jid_hash then
556 session_jid = to_jid;
560 if session_jid == nil then return nil; end
561 stanza.attr.from, stanza.attr.to, stanza.attr.id = from_occupant_jid, session_jid, id;
563 log("debug", "%s sent private iq stanza to %s (%s)", from, to, stanza.attr.to);
564 self:route_stanza(stanza);
565 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
567 else -- Type is "get" or "set"
568 local current_nick = self:get_occupant_jid(from);
569 if not current_nick then
570 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
573 if not occupant then -- recipient not in room
574 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
577 do -- construct_stanza_id
578 stanza.attr.id = base64.encode(occupant.jid.."\0"..stanza.attr.id.."\0"..md5(from));
580 stanza.attr.from, stanza.attr.to = current_nick, occupant.jid;
581 log("debug", "%s sent private iq stanza to %s (%s)", from, to, occupant.jid);
582 if stanza.tags[1].attr.xmlns == 'vcard-temp' then
583 stanza.attr.to = jid_bare(stanza.attr.to);
585 self:route_stanza(stanza);
586 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
591 function room_mt:handle_message_to_occupant(origin, stanza)
592 local from, to = stanza.attr.from, stanza.attr.to;
593 local current_nick = self:get_occupant_jid(from);
594 local type = stanza.attr.type;
595 if not current_nick then -- not in room
596 if type ~= "error" then
597 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
601 if type == "groupchat" then -- groupchat messages not allowed in PM
602 origin.send(st.error_reply(stanza, "modify", "bad-request"));
604 elseif type == "error" and is_kickable_error(stanza) then
605 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
606 return self:handle_kickable(origin, stanza); -- send unavailable
609 local o_data = self:get_occupant_by_nick(to);
611 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
614 log("debug", "%s sent private message stanza to %s (%s)", from, to, o_data.jid);
615 stanza:tag("x", { xmlns = "http://jabber.org/protocol/muc#user" }):up();
616 stanza.attr.from = current_nick;
617 self:route_to_occupant(o_data, stanza)
618 -- TODO: Remove x tag?
619 stanza.attr.from = from;
623 function room_mt:send_form(origin, stanza)
624 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
625 :add_child(self:get_form_layout(stanza.attr.from):form())
629 function room_mt:get_form_layout(actor)
630 local form = dataform.new({
631 title = "Configuration for "..self.jid,
632 instructions = "Complete and submit this form to configure the room.",
636 value = 'http://jabber.org/protocol/muc#roomconfig'
639 return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
642 function room_mt:process_form(origin, stanza)
643 local form = stanza.tags[1]:get_child("x", "jabber:x:data");
644 if form.attr.type == "cancel" then
645 origin.send(st.reply(stanza));
646 elseif form.attr.type == "submit" then
648 if form.tags[1] == nil then -- Instant room
651 fields = self:get_form_layout(stanza.attr.from):data(form);
652 if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then
653 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration"));
658 local event = {room = self; origin = origin; stanza = stanza; fields = fields; status_codes = {};};
659 function event.update_option(name, field, allowed)
660 local new = fields[field];
661 if new == nil then return; end
662 if allowed and not allowed[new] then return; end
663 if new == self["get_"..name](self) then return; end
664 event.status_codes["104"] = true;
665 self["set_"..name](self, new);
668 module:fire_event("muc-config-submitted", event);
670 if self.save then self:save(true); end
671 origin.send(st.reply(stanza));
673 if next(event.status_codes) then
674 local msg = st.message({type='groupchat', from=self.jid})
675 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
676 for code in pairs(event.status_codes) do
677 msg:tag("status", {code = code;}):up();
680 self:broadcast_message(msg);
683 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form"));
688 -- Removes everyone from the room
689 function room_mt:clear(x)
690 x = x or st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
691 local occupants_updated = {};
692 for nick, occupant in self:each_occupant() do
694 self:save_occupant(occupant);
695 occupants_updated[occupant] = true;
697 for occupant in pairs(occupants_updated) do
698 self:publicise_occupant_status(occupant, x);
699 module:fire_event("muc-occupant-left", { room = self; nick = occupant.nick; occupant = occupant;});
703 function room_mt:destroy(newjid, reason, password)
704 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
705 :tag("item", { affiliation='none', role='none' }):up()
706 :tag("destroy", {jid=newjid});
707 if reason then x:tag("reason"):text(reason):up(); end
708 if password then x:tag("password"):text(password):up(); end
711 module:fire_event("muc-room-destroyed", { room = self });
714 function room_mt:handle_disco_info_get_query(origin, stanza)
715 origin.send(self:get_disco_info(stanza));
719 function room_mt:handle_disco_items_get_query(origin, stanza)
720 origin.send(self:get_disco_items(stanza));
724 function room_mt:handle_admin_query_set_command(origin, stanza)
725 local item = stanza.tags[1].tags[1];
727 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
729 if item.attr.jid then -- Validate provided JID
730 item.attr.jid = jid_prep(item.attr.jid);
731 if not item.attr.jid then
732 origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
736 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
737 local occupant = self:get_occupant_by_nick(self.jid.."/"..item.attr.nick);
738 if occupant then item.attr.jid = occupant.jid; end
739 elseif not item.attr.nick and item.attr.jid then
740 local nick = self:get_occupant_jid(item.attr.jid);
741 if nick then item.attr.nick = select(3, jid_split(nick)); end
743 local actor = stanza.attr.from;
744 local reason = item:get_child_text("reason");
745 local success, errtype, err
746 if item.attr.affiliation and item.attr.jid and not item.attr.role then
747 success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, reason);
748 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
749 success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, reason);
751 success, errtype, err = nil, "cancel", "bad-request";
754 origin.send(st.error_reply(stanza, errtype, err));
756 origin.send(st.reply(stanza));
761 function room_mt:handle_admin_query_get_command(origin, stanza)
762 local actor = stanza.attr.from;
763 local affiliation = self:get_affiliation(actor);
764 local item = stanza.tags[1].tags[1];
765 local _aff = item.attr.affiliation;
766 local _aff_rank = valid_affiliations[_aff or "none"];
767 local _rol = item.attr.role;
768 if _aff and _aff_rank and not _rol then
769 -- You need to be at least an admin, and be requesting info about your affifiliation or lower
770 -- e.g. an admin can't ask for a list of owners
771 local affiliation_rank = valid_affiliations[affiliation or "none"];
772 if affiliation_rank >= valid_affiliations.admin and affiliation_rank >= _aff_rank then
773 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
774 for jid in self:each_affiliation(_aff or "none") do
775 reply:tag("item", {affiliation = _aff, jid = jid}):up();
777 origin.send(reply:up());
780 origin.send(st.error_reply(stanza, "auth", "forbidden"));
783 elseif _rol and valid_roles[_rol or "none"] and not _aff then
784 local role = self:get_role(self:get_occupant_jid(actor)) or self:get_default_role(affiliation);
785 if valid_roles[role or "none"] >= valid_roles.moderator then
786 if _rol == "none" then _rol = nil; end
787 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
788 -- TODO: whois check here? (though fully anonymous rooms are not supported)
789 for occupant_jid, occupant in self:each_occupant() do
790 if occupant.role == _rol then
791 local nick = select(3,jid_split(occupant_jid));
792 self:build_item_list(occupant, reply, false, nick);
795 origin.send(reply:up());
798 origin.send(st.error_reply(stanza, "auth", "forbidden"));
802 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
807 function room_mt:handle_owner_query_get_to_room(origin, stanza)
808 if self:get_affiliation(stanza.attr.from) ~= "owner" then
809 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
813 self:send_form(origin, stanza);
816 function room_mt:handle_owner_query_set_to_room(origin, stanza)
817 if self:get_affiliation(stanza.attr.from) ~= "owner" then
818 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
822 local child = stanza.tags[1].tags[1];
824 origin.send(st.error_reply(stanza, "modify", "bad-request"));
826 elseif child.name == "destroy" then
827 local newjid = child.attr.jid;
828 local reason = child:get_child_text("reason");
829 local password = child:get_child_text("password");
830 self:destroy(newjid, reason, password);
831 origin.send(st.reply(stanza));
833 elseif child.name == "x" and child.attr.xmlns == "jabber:x:data" then
834 return self:process_form(origin, stanza);
836 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
841 function room_mt:handle_groupchat_to_room(origin, stanza)
842 local from = stanza.attr.from;
843 local occupant = self:get_occupant_by_real_jid(from);
844 if module:fire_event("muc-occupant-groupchat", {
845 room = self; origin = origin; stanza = stanza; from = from; occupant = occupant;
846 }) then return true; end
847 stanza.attr.from = occupant.nick;
848 self:broadcast_message(stanza);
849 stanza.attr.from = from;
854 module:hook("muc-occupant-groupchat", function(event)
855 local role_rank = valid_roles[event.occupant and event.occupant.role or "none"];
856 if role_rank <= valid_roles.none then
857 event.origin.send(st.error_reply(event.stanza, "cancel", "not-acceptable"));
859 elseif role_rank <= valid_roles.visitor then
860 event.origin.send(st.error_reply(event.stanza, "auth", "forbidden"));
865 -- hack - some buggy clients send presence updates to the room rather than their nick
866 function room_mt:handle_presence_to_room(origin, stanza)
867 local current_nick = self:get_occupant_jid(stanza.attr.from);
870 local to = stanza.attr.to;
871 stanza.attr.to = current_nick;
872 handled = self:handle_presence_to_occupant(origin, stanza);
878 -- Need visitor role or higher to invite
879 module:hook("muc-pre-invite", function(event)
880 local room, stanza = event.room, event.stanza;
881 local _from, _to = stanza.attr.from, stanza.attr.to;
882 local inviter = room:get_occupant_by_real_jid(_from);
883 local role = inviter and inviter.role or room:get_default_role(room:get_affiliation(_from));
884 if valid_roles[role or "none"] <= valid_roles.visitor then
885 event.origin.send(st.error_reply(stanza, "auth", "forbidden"));
890 function room_mt:handle_mediated_invite(origin, stanza)
891 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
892 local invitee = jid_prep(payload.attr.to);
894 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
896 elseif module:fire_event("muc-pre-invite", {room = self, origin = origin, stanza = stanza}) then
899 local invite = muc_util.filter_muc_x(st.clone(stanza));
900 invite.attr.from = self.jid;
901 invite.attr.to = invitee;
902 invite:tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
903 :tag('invite', {from = stanza.attr.from;})
904 :tag('reason'):text(payload:get_child_text("reason")):up()
907 if not module:fire_event("muc-invite", {room = self, stanza = invite, origin = origin, incoming = stanza}) then
908 self:route_stanza(invite);
913 -- COMPAT: Some older clients expect this
914 module:hook("muc-invite", function(event)
915 local room, stanza = event.room, event.stanza;
916 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
917 local reason = invite:get_child_text("reason");
918 stanza:tag('x', {xmlns = "jabber:x:conference"; jid = room.jid;})
923 -- Add a plain message for clients which don't support invites
924 module:hook("muc-invite", function(event)
925 local room, stanza = event.room, event.stanza;
926 if not stanza:get_child("body") then
927 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
928 local reason = invite:get_child_text("reason") or "";
930 :text(invite.attr.from.." invited you to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
935 function room_mt:handle_mediated_decline(origin, stanza)
936 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
937 local declinee = jid_prep(payload.attr.to);
939 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
941 elseif module:fire_event("muc-pre-decline", {room = self, origin = origin, stanza = stanza}) then
944 local decline = muc_util.filter_muc_x(st.clone(stanza));
945 decline.attr.from = self.jid;
946 decline.attr.to = declinee;
947 decline:tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
948 :tag("decline", {from = stanza.attr.from})
949 :tag("reason"):text(payload:get_child_text("reason")):up()
952 if not module:fire_event("muc-decline", {room = self, stanza = decline, origin = origin, incoming = stanza}) then
953 local declinee = decline.attr.to; -- re-fetch, in case event modified it
955 if jid_bare(declinee) == self.jid then -- declinee jid is already an in-room jid
956 occupant = self:get_occupant_by_nick(declinee);
959 self:route_to_occupant(occupant, decline);
961 self:route_stanza(decline);
967 -- Add a plain message for clients which don't support declines
968 module:hook("muc-decline", function(event)
969 local room, stanza = event.room, event.stanza;
970 if not stanza:get_child("body") then
971 local decline = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
972 local reason = decline:get_child_text("reason") or "";
974 :text(decline.attr.from.." declined your invite to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
979 function room_mt:handle_message_to_room(origin, stanza)
980 local type = stanza.attr.type;
981 if type == "groupchat" then
982 return self:handle_groupchat_to_room(origin, stanza)
983 elseif type == "error" and is_kickable_error(stanza) then
984 return self:handle_kickable(origin, stanza)
985 elseif type == nil then
986 local x = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
988 local payload = x.tags[1];
989 if payload == nil then
991 elseif payload.name == "invite" and payload.attr.to then
992 return self:handle_mediated_invite(origin, stanza)
993 elseif payload.name == "decline" and payload.attr.to then
994 return self:handle_mediated_decline(origin, stanza)
996 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
1002 function room_mt:route_stanza(stanza)
1003 module:send(stanza);
1006 function room_mt:get_affiliation(jid)
1007 local node, host, resource = jid_split(jid);
1008 local bare = node and node.."@"..host or host;
1009 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
1010 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
1014 -- Iterates over jid, affiliation pairs
1015 function room_mt:each_affiliation(with_affiliation)
1016 if not with_affiliation then
1017 return pairs(self._affiliations);
1019 return function(_affiliations, jid)
1021 repeat -- Iterate until we get a match
1022 jid, affiliation = next(_affiliations, jid);
1023 until jid == nil or affiliation == with_affiliation
1024 return jid, affiliation;
1025 end, self._affiliations, nil
1029 function room_mt:set_affiliation(actor, jid, affiliation, reason)
1030 if not actor then return nil, "modify", "not-acceptable"; end;
1032 local node, host, resource = jid_split(jid);
1033 if not host then return nil, "modify", "not-acceptable"; end
1034 jid = jid_join(node, host); -- Bare
1035 local is_host_only = node == nil;
1037 if valid_affiliations[affiliation or "none"] == nil then
1038 return nil, "modify", "not-acceptable";
1040 affiliation = affiliation ~= "none" and affiliation or nil; -- coerces `affiliation == false` to `nil`
1042 local target_affiliation = self._affiliations[jid]; -- Raw; don't want to check against host
1043 local is_downgrade = valid_affiliations[target_affiliation or "none"] > valid_affiliations[affiliation or "none"];
1045 if actor == true then
1046 actor = nil -- So we can pass it safely to 'publicise_occupant_status' below
1048 local actor_affiliation = self:get_affiliation(actor);
1049 if actor_affiliation == "owner" then
1050 if jid_bare(actor) == jid then -- self change
1051 -- need at least one owner
1052 local is_last = true;
1053 for j in self:each_affiliation("owner") do
1054 if j ~= jid then is_last = false; break; end
1057 return nil, "cancel", "conflict";
1060 -- owners can do anything else
1061 elseif affiliation == "owner" or affiliation == "admin"
1062 or actor_affiliation ~= "admin"
1063 or target_affiliation == "owner" or target_affiliation == "admin" then
1064 -- Can't demote owners or other admins
1065 return nil, "cancel", "not-allowed";
1069 -- Set in 'database'
1070 self._affiliations[jid] = affiliation;
1073 local role = self:get_default_role(affiliation);
1074 local role_rank = valid_roles[role or "none"];
1075 local occupants_updated = {}; -- Filled with old roles
1076 for nick, occupant in self:each_occupant() do
1077 if occupant.bare_jid == jid or (
1078 -- Outcast can be by host.
1079 is_host_only and affiliation == "outcast" and select(2, jid_split(occupant.bare_jid)) == host
1081 -- need to publcize in all cases; as affiliation in <item/> has changed.
1082 occupants_updated[occupant] = occupant.role;
1083 if occupant.role ~= role and (
1085 valid_roles[occupant.role or "none"] < role_rank -- upgrade
1087 occupant.role = role;
1088 self:save_occupant(occupant);
1093 -- Tell the room of the new occupant affiliations+roles
1094 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1095 if not role then -- getting kicked
1096 if affiliation == "outcast" then
1097 x:tag("status", {code="301"}):up(); -- banned
1099 x:tag("status", {code="321"}):up(); -- affiliation change
1102 local is_semi_anonymous = self:get_whois() == "moderators";
1103 for occupant, old_role in pairs(occupants_updated) do
1104 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1105 if occupant.role == nil then
1106 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
1107 elseif is_semi_anonymous and
1108 (old_role == "moderator" and occupant.role ~= "moderator") or
1109 (old_role ~= "moderator" and occupant.role == "moderator") then -- Has gained or lost moderator status
1110 -- Send everyone else's presences (as jid visibility has changed)
1111 for real_jid in occupant:each_session() do
1112 self:send_occupant_list(real_jid, function(occupant_jid, occupant)
1113 return occupant.bare_jid ~= jid;
1119 if self.save then self:save(); end
1121 module:fire_event("muc-set-affiliation", {
1125 affiliation = affiliation or "none";
1127 previous_affiliation = target_affiliation;
1128 in_room = next(occupants_updated) ~= nil;
1134 function room_mt:get_role(nick)
1135 local occupant = self:get_occupant_by_nick(nick);
1136 return occupant and occupant.role or nil;
1139 function room_mt:set_role(actor, occupant_jid, role, reason)
1140 if not actor then return nil, "modify", "not-acceptable"; end
1142 local occupant = self:get_occupant_by_nick(occupant_jid);
1143 if not occupant then return nil, "modify", "not-acceptable"; end
1145 if valid_roles[role or "none"] == nil then
1146 return nil, "modify", "not-acceptable";
1148 role = role ~= "none" and role or nil; -- coerces `role == false` to `nil`
1150 if actor == true then
1151 actor = nil -- So we can pass it safely to 'publicise_occupant_status' below
1153 -- Can't do anything to other owners or admins
1154 local occupant_affiliation = self:get_affiliation(occupant.bare_jid);
1155 if occupant_affiliation == "owner" or occupant_affiliation == "admin" then
1156 return nil, "cancel", "not-allowed";
1159 -- If you are trying to give or take moderator role you need to be an owner or admin
1160 if occupant.role == "moderator" or role == "moderator" then
1161 local actor_affiliation = self:get_affiliation(actor);
1162 if actor_affiliation ~= "owner" and actor_affiliation ~= "admin" then
1163 return nil, "cancel", "not-allowed";
1167 -- Need to be in the room and a moderator
1168 local actor_occupant = self:get_occupant_by_real_jid(actor);
1169 if not actor_occupant or actor_occupant.role ~= "moderator" then
1170 return nil, "cancel", "not-allowed";
1174 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1176 x:tag("status", {code = "307"}):up();
1178 occupant.role = role;
1179 self:save_occupant(occupant);
1180 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1182 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
1187 local whois = module:require "muc/whois";
1188 room_mt.get_whois = whois.get;
1189 room_mt.set_whois = whois.set;
1191 local _M = {}; -- module "muc"
1193 function _M.new_room(jid, config)
1194 return setmetatable({
1204 _M.room_mt = room_mt;