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, reason)
135 x:tag("item", {affiliation = affiliation; role = role; jid = jid; nick = nick;})
137 x:tag("actor", actor):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, reason)
148 local affiliation = self:get_affiliation(occupant.bare_jid) or "none";
149 local role = occupant.role or "none";
152 actor_attr = {nick = select(3,jid_split(self:get_occupant_jid(actor)))};
155 add_item(x, affiliation, role, nil, nick, actor_attr, reason);
158 actor_attr.jid = actor;
160 for real_jid, session in occupant:each_session() do
161 add_item(x, affiliation, role, real_jid, nick, actor_attr, reason);
167 function room_mt:broadcast_message(stanza)
168 if module:fire_event("muc-broadcast-message", {room = self, stanza = stanza}) then
171 self:broadcast(stanza);
175 -- Broadcast a stanza to all occupants in the room.
176 -- optionally checks conditional called with (nick, occupant)
177 function room_mt:broadcast(stanza, cond_func)
178 for nick, occupant in self:each_occupant() do
179 if cond_func == nil or cond_func(nick, occupant) then
180 self:route_to_occupant(occupant, stanza)
185 local function can_see_real_jids(whois, occupant)
186 if whois == "anyone" then
188 elseif whois == "moderators" then
189 return valid_roles[occupant.role or "none"] >= valid_roles.moderator;
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
198 if occupant.role ~= nil then
199 -- Try to use main jid's presence
200 local pr = occupant:get_presence();
202 base_presence = st.clone(pr);
205 base_presence = base_presence or st.presence {from = occupant.nick; type = "unavailable";};
207 -- Fire event (before full_p and anon_p are created)
208 module:fire_event("muc-broadcast-presence", {
209 room = self; stanza = base_presence; x = base_x;
210 occupant = occupant; nick = nick; actor = actor;
214 local function get_presence(is_anonymous)
215 local x = st.clone(base_x);
216 self:build_item_list(occupant, x, is_anonymous, nick, actor, reason);
217 return st.clone(base_presence):add_child(x), x;
220 local full_p, full_x = get_presence(false);
222 -- Create anon_p lazily
223 local anon_p, anon_x;
224 local function get_anon_p()
225 if anon_p == nil then
226 anon_p, anon_x = get_presence(true);
228 return anon_p, anon_x;
231 local whois = self:get_whois();
234 for nick, n_occupant in self:each_occupant() do
235 if nick ~= occupant.nick then
237 if can_see_real_jids(whois, n_occupant) or occupant.bare_jid == n_occupant.bare_jid then
242 self:route_to_occupant(n_occupant, pr);
246 -- Presences for occupant itself
247 full_x:tag("status", {code = "110";}):up();
248 if occupant.role == nil then
249 -- They get an unavailable
250 self:route_to_occupant(occupant, full_p);
252 -- use their own presences as templates
253 for full_jid, pr in occupant:each_session() do
255 pr.attr.to = full_jid;
256 -- You can always see your own full jids
257 pr:add_child(full_x);
258 self:route_stanza(pr);
263 function room_mt:send_occupant_list(to, filter)
264 local to_bare = jid_bare(to);
265 local is_anonymous = false;
266 local whois = self:get_whois();
267 if whois ~= "anyone" then
268 local affiliation = self:get_affiliation(to);
269 if affiliation ~= "admin" and affiliation ~= "owner" then
270 local occupant = self:get_occupant_by_real_jid(to);
271 if not (occupant and can_see_real_jids(whois, occupant)) then
276 for occupant_jid, occupant in self:each_occupant() do
277 if filter == nil or filter(occupant_jid, occupant) then
278 local x = st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
279 self:build_item_list(occupant, x, is_anonymous and to_bare ~= occupant.bare_jid); -- can always see your own jids
280 local pres = st.clone(occupant:get_presence());
283 self:route_stanza(pres);
288 function room_mt:get_disco_info(stanza)
289 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#info");
290 local form = dataform.new {
291 { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" };
293 module:fire_event("muc-disco#info", {room = self; reply = reply; form = form;});
294 reply:add_child(form:form(nil, "result"));
297 module:hook("muc-disco#info", function(event)
298 event.reply:tag("feature", {var = "http://jabber.org/protocol/muc"}):up();
300 module:hook("muc-disco#info", function(event)
301 local count = iterators.count(event.room:each_occupant());
302 table.insert(event.form, { name = "muc#roominfo_occupants", label = "Number of occupants", value = tostring(count) });
305 function room_mt:get_disco_items(stanza)
306 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
307 for room_jid in self:each_occupant() do
308 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
313 function room_mt:handle_kickable(origin, stanza)
314 local real_jid = stanza.attr.from;
315 local occupant = self:get_occupant_by_real_jid(real_jid);
316 if occupant == nil then return nil; end
317 local type, condition, text = stanza:get_error();
318 local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
320 error_message = error_message..": "..text;
322 occupant:set_session(real_jid, st.presence({type="unavailable"})
323 :tag('status'):text(error_message));
324 self:save_occupant(occupant);
325 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
326 :tag("status", {code = "307"})
327 self:publicise_occupant_status(occupant, x);
328 if occupant.jid == real_jid then -- Was last session
329 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
334 -- Give the room creator owner affiliation
335 module:hook("muc-room-pre-create", function(event)
336 event.room:set_affiliation(true, jid_bare(event.stanza.attr.from), "owner");
339 -- check if user is banned
340 module:hook("muc-occupant-pre-join", function(event)
341 local room, stanza = event.room, event.stanza;
342 local affiliation = room:get_affiliation(stanza.attr.from);
343 if affiliation == "outcast" then
344 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
345 reply.tags[1].attr.code = "403";
346 event.origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
351 function room_mt:handle_presence_to_occupant(origin, stanza)
352 local type = stanza.attr.type;
353 if type == "error" then -- error, kick em out!
354 return self:handle_kickable(origin, stanza)
355 elseif type == nil or type == "unavailable" then
356 local real_jid = stanza.attr.from;
357 local bare_jid = jid_bare(real_jid);
358 local orig_occupant, dest_occupant;
359 local is_new_room = next(self._affiliations) == nil;
361 if type == "unavailable" then return true; end -- Unavailable from someone not in the room
362 if module:fire_event("muc-room-pre-create", {
366 }) then return true; end
368 orig_occupant = self:get_occupant_by_real_jid(real_jid);
369 if type == "unavailable" and orig_occupant == nil then return true; end -- Unavailable from someone not in the room
371 local is_first_dest_session;
372 if type == "unavailable" then
373 -- dest_occupant = nil
374 elseif orig_occupant and orig_occupant.nick == stanza.attr.to then -- Just a presence update
375 log("debug", "presence update for %s from session %s", orig_occupant.nick, real_jid);
376 dest_occupant = orig_occupant;
378 local dest_jid = stanza.attr.to;
379 dest_occupant = self:get_occupant_by_nick(dest_jid);
380 if dest_occupant == nil then
381 log("debug", "no occupant found for %s; creating new occupant object for %s", dest_jid, real_jid);
382 is_first_dest_session = true;
383 dest_occupant = self:new_occupant(bare_jid, dest_jid);
385 is_first_dest_session = false;
388 local is_last_orig_session;
389 if orig_occupant ~= nil then
390 -- Is there are least 2 sessions?
391 local iter, ob, last = orig_occupant:each_session();
392 is_last_orig_session = iter(ob, iter(ob, last)) == nil;
395 local event, event_name = {
399 is_first_session = is_first_dest_session;
400 is_last_session = is_last_orig_session;
402 if orig_occupant == nil then
403 event_name = "muc-occupant-pre-join";
404 event.is_new_room = is_new_room;
405 event.occupant = dest_occupant;
406 elseif dest_occupant == nil then
407 event_name = "muc-occupant-pre-leave";
408 event.occupant = orig_occupant;
410 event_name = "muc-occupant-pre-change";
411 event.orig_occupant = orig_occupant;
412 event.dest_occupant = dest_occupant;
414 if module:fire_event(event_name, event) then return true; end
416 -- Check for nick conflicts
417 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
418 log("debug", "%s couldn't join due to nick conflict: %s", real_jid, dest_occupant.nick);
419 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
420 reply.tags[1].attr.code = "409";
421 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
425 -- Send presence stanza about original occupant
426 if orig_occupant ~= nil and orig_occupant ~= dest_occupant then
427 local orig_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
429 if dest_occupant == nil then -- Session is leaving
430 log("debug", "session %s is leaving occupant %s", real_jid, orig_occupant.nick);
431 if is_last_orig_session then
432 orig_occupant.role = nil;
434 orig_occupant:set_session(real_jid, stanza);
436 log("debug", "session %s is changing from occupant %s to %s", real_jid, orig_occupant.nick, dest_occupant.nick);
437 local generated_unavail = st.presence {from = orig_occupant.nick, to = real_jid, type = "unavailable"};
438 orig_occupant:set_session(real_jid, generated_unavail);
439 dest_nick = select(3, jid_split(dest_occupant.nick));
440 if not is_first_dest_session then -- User is swapping into another pre-existing session
441 log("debug", "session %s is swapping into multisession %s, showing it leave.", real_jid, dest_occupant.nick);
442 -- Show the other session leaving
443 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
444 :tag("status"):text("you are joining pre-existing session " .. dest_nick):up();
445 add_item(x, self:get_affiliation(bare_jid), "none");
446 local pr = st.presence{from = dest_occupant.nick, to = real_jid, type = "unavailable"}
448 self:route_stanza(pr);
450 if is_first_dest_session and is_last_orig_session then -- Normal nick change
451 log("debug", "no sessions in %s left; publically marking as nick change", orig_occupant.nick);
452 orig_x:tag("status", {code = "303";}):up();
453 else -- The session itself always needs to see a nick change
454 -- don't want to get our old nick's available presence,
455 -- so remove our session from there, and manually generate an unavailable
456 orig_occupant:remove_session(real_jid);
457 log("debug", "generating nick change for %s", real_jid);
458 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
459 -- self:build_item_list(orig_occupant, x, false, dest_nick); -- COMPAT: clients get confused if they see other items besides their own
460 add_item(x, self:get_affiliation(bare_jid), orig_occupant.role, real_jid, dest_nick);
461 x:tag("status", {code = "303";}):up();
462 x:tag("status", {code = "110";}):up();
463 self:route_stanza(generated_unavail:add_child(x));
464 dest_nick = nil; -- set dest_nick to nil; so general populance doesn't see it for whole orig_occupant
467 self:save_occupant(orig_occupant);
468 self:publicise_occupant_status(orig_occupant, orig_x, dest_nick);
470 if is_last_orig_session then
471 module:fire_event("muc-occupant-left", {room = self; nick = orig_occupant.nick; occupant = orig_occupant;});
475 if dest_occupant ~= nil then
476 dest_occupant:set_session(real_jid, stanza);
477 local dest_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
479 dest_x:tag("status", {code = "201"}):up();
481 if orig_occupant == nil and self:get_whois() == "anyone" then
482 dest_x:tag("status", {code = "100"}):up();
484 self:save_occupant(dest_occupant);
486 if orig_occupant == nil then
487 -- Send occupant list to newly joined user
488 self:send_occupant_list(real_jid, function(nick, occupant)
489 -- Don't include self
490 return occupant:get_presence(real_jid) == nil;
493 self:publicise_occupant_status(dest_occupant, dest_x);
495 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
496 log("debug", "session %s split nicks; showing %s rejoining", real_jid, orig_occupant.nick);
497 -- Show the original nick joining again
498 local pr = st.clone(orig_occupant:get_presence());
499 pr.attr.to = real_jid;
500 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
501 self:build_item_list(orig_occupant, x, false);
502 -- TODO: new status code to inform client this was the multi-session it left?
504 self:route_stanza(pr);
507 if orig_occupant == nil then
508 if is_first_dest_session then
509 module:fire_event("muc-occupant-joined", {room = self; nick = dest_occupant.nick; occupant = dest_occupant;});
511 module:fire_event("muc-occupant-session-new", {room = self; nick = dest_occupant.nick; occupant = dest_occupant; stanza = stanza; jid = real_jid;});
514 elseif type ~= 'result' then -- bad type
515 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
516 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
522 function room_mt:handle_iq_to_occupant(origin, stanza)
523 local from, to = stanza.attr.from, stanza.attr.to;
524 local type = stanza.attr.type;
525 local id = stanza.attr.id;
526 local occupant = self:get_occupant_by_nick(to);
527 if (type == "error" or type == "result") then
528 do -- deconstruct_stanza_id
529 if not occupant then return nil; end
530 local from_jid, id, to_jid_hash = (base64.decode(stanza.attr.id) or ""):match("^(.+)%z(.*)%z(.+)$");
531 if not(from == from_jid or from == jid_bare(from_jid)) then return nil; end
532 local from_occupant_jid = self:get_occupant_jid(from_jid);
533 if from_occupant_jid == nil then return nil; end
535 for to_jid in occupant:each_session() do
536 if md5(to_jid) == to_jid_hash then
537 session_jid = to_jid;
541 if session_jid == nil then return nil; end
542 stanza.attr.from, stanza.attr.to, stanza.attr.id = from_occupant_jid, session_jid, id;
544 log("debug", "%s sent private iq stanza to %s (%s)", from, to, stanza.attr.to);
545 self:route_stanza(stanza);
546 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
548 else -- Type is "get" or "set"
549 local current_nick = self:get_occupant_jid(from);
550 if not current_nick then
551 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
554 if not occupant then -- recipient not in room
555 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
558 do -- construct_stanza_id
559 stanza.attr.id = base64.encode(occupant.jid.."\0"..stanza.attr.id.."\0"..md5(from));
561 stanza.attr.from, stanza.attr.to = current_nick, occupant.jid;
562 log("debug", "%s sent private iq stanza to %s (%s)", from, to, occupant.jid);
563 if stanza.tags[1].attr.xmlns == 'vcard-temp' then
564 stanza.attr.to = jid_bare(stanza.attr.to);
566 self:route_stanza(stanza);
567 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
572 function room_mt:handle_message_to_occupant(origin, stanza)
573 local from, to = stanza.attr.from, stanza.attr.to;
574 local current_nick = self:get_occupant_jid(from);
575 local type = stanza.attr.type;
576 if not current_nick then -- not in room
577 if type ~= "error" then
578 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
582 if type == "groupchat" then -- groupchat messages not allowed in PM
583 origin.send(st.error_reply(stanza, "modify", "bad-request"));
585 elseif type == "error" and is_kickable_error(stanza) then
586 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
587 return self:handle_kickable(origin, stanza); -- send unavailable
590 local o_data = self:get_occupant_by_nick(to);
592 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
595 log("debug", "%s sent private message stanza to %s (%s)", from, to, o_data.jid);
596 stanza:tag("x", { xmlns = "http://jabber.org/protocol/muc#user" }):up();
597 stanza.attr.from = current_nick;
598 self:route_to_occupant(o_data, stanza)
599 -- TODO: Remove x tag?
600 stanza.attr.from = from;
604 function room_mt:send_form(origin, stanza)
605 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
606 :add_child(self:get_form_layout(stanza.attr.from):form())
610 function room_mt:get_form_layout(actor)
611 local form = dataform.new({
612 title = "Configuration for "..self.jid,
613 instructions = "Complete and submit this form to configure the room.",
617 value = 'http://jabber.org/protocol/muc#roomconfig'
620 return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
623 function room_mt:process_form(origin, stanza)
624 local form = stanza.tags[1]:get_child("x", "jabber:x:data");
625 if form.attr.type == "cancel" then
626 origin.send(st.reply(stanza));
627 elseif form.attr.type == "submit" then
629 if form.tags[1] == nil then -- Instant room
632 fields = self:get_form_layout(stanza.attr.from):data(form);
633 if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then
634 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration"));
639 local event = {room = self; origin = origin; stanza = stanza; fields = fields; status_codes = {};};
640 function event.update_option(name, field, allowed)
641 local new = fields[field];
642 if new == nil then return; end
643 if allowed and not allowed[new] then return; end
644 if new == self["get_"..name](self) then return; end
645 event.status_codes["104"] = true;
646 self["set_"..name](self, new);
649 module:fire_event("muc-config-submitted", event);
651 if self.save then self:save(true); end
652 origin.send(st.reply(stanza));
654 if next(event.status_codes) then
655 local msg = st.message({type='groupchat', from=self.jid})
656 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
657 for code in pairs(event.status_codes) do
658 msg:tag("status", {code = code;}):up();
661 self:broadcast_message(msg);
664 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form"));
669 -- Removes everyone from the room
670 function room_mt:clear(x)
671 x = x or st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
672 local occupants_updated = {};
673 for nick, occupant in self:each_occupant() do
675 self:save_occupant(occupant);
676 occupants_updated[occupant] = true;
678 for occupant in pairs(occupants_updated) do
679 self:publicise_occupant_status(occupant, x);
680 module:fire_event("muc-occupant-left", { room = self; nick = occupant.nick; occupant = occupant;});
684 function room_mt:destroy(newjid, reason, password)
685 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
686 :tag("item", { affiliation='none', role='none' }):up()
687 :tag("destroy", {jid=newjid});
688 if reason then x:tag("reason"):text(reason):up(); end
689 if password then x:tag("password"):text(password):up(); end
692 module:fire_event("muc-room-destroyed", { room = self });
695 function room_mt:handle_disco_info_get_query(origin, stanza)
696 origin.send(self:get_disco_info(stanza));
700 function room_mt:handle_disco_items_get_query(origin, stanza)
701 origin.send(self:get_disco_items(stanza));
705 function room_mt:handle_admin_query_set_command(origin, stanza)
706 local item = stanza.tags[1].tags[1];
707 if item.attr.jid then -- Validate provided JID
708 item.attr.jid = jid_prep(item.attr.jid);
709 if not item.attr.jid then
710 origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
714 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
715 local occupant = self:get_occupant_by_nick(self.jid.."/"..item.attr.nick);
716 if occupant then item.attr.jid = occupant.jid; end
717 elseif not item.attr.nick and item.attr.jid then
718 local nick = self:get_occupant_jid(item.attr.jid);
719 if nick then item.attr.nick = select(3, jid_split(nick)); end
721 local actor = stanza.attr.from;
722 local reason = item:get_child_text("reason");
723 local success, errtype, err
724 if item.attr.affiliation and item.attr.jid and not item.attr.role then
725 success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, reason);
726 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
727 success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, reason);
729 success, errtype, err = nil, "cancel", "bad-request";
731 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
732 origin.send(st.reply(stanza));
736 function room_mt:handle_admin_query_get_command(origin, stanza)
737 local actor = stanza.attr.from;
738 local affiliation = self:get_affiliation(actor);
739 local item = stanza.tags[1].tags[1];
740 local _aff = item.attr.affiliation;
741 local _aff_rank = valid_affiliations[_aff or "none"];
742 local _rol = item.attr.role;
743 if _aff and _aff_rank and not _rol then
744 -- You need to be at least an admin, and be requesting info about your affifiliation or lower
745 -- e.g. an admin can't ask for a list of owners
746 local affiliation_rank = valid_affiliations[affiliation];
747 if affiliation_rank >= valid_affiliations.admin and affiliation_rank >= _aff_rank then
748 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
749 for jid in self:each_affiliation(_aff or "none") do
750 reply:tag("item", {affiliation = _aff, jid = jid}):up();
752 origin.send(reply:up());
755 origin.send(st.error_reply(stanza, "auth", "forbidden"));
758 elseif _rol and valid_roles[_rol or "none"] and not _aff then
759 local role = self:get_role(self:get_occupant_jid(actor)) or self:get_default_role(affiliation);
760 if valid_roles[role or "none"] >= valid_roles.moderator then
761 if _rol == "none" then _rol = nil; end
762 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
763 -- TODO: whois check here? (though fully anonymous rooms are not supported)
764 for occupant_jid, occupant in self:each_occupant() do
765 if occupant.role == _rol then
766 local nick = select(3,jid_split(occupant_jid));
767 self:build_item_list(occupant, reply, false, nick);
770 origin.send(reply:up());
773 origin.send(st.error_reply(stanza, "auth", "forbidden"));
777 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
782 function room_mt:handle_owner_query_get_to_room(origin, stanza)
783 if self:get_affiliation(stanza.attr.from) ~= "owner" then
784 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
788 self:send_form(origin, stanza);
791 function room_mt:handle_owner_query_set_to_room(origin, stanza)
792 if self:get_affiliation(stanza.attr.from) ~= "owner" then
793 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
797 local child = stanza.tags[1].tags[1];
799 origin.send(st.error_reply(stanza, "modify", "bad-request"));
801 elseif child.name == "destroy" then
802 local newjid = child.attr.jid;
803 local reason = child:get_child_text("reason");
804 local password = child:get_child_text("password");
805 self:destroy(newjid, reason, password);
806 origin.send(st.reply(stanza));
808 elseif child.name == "x" and child.attr.xmlns == "jabber:x:data" then
809 return self:process_form(origin, stanza);
811 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
816 function room_mt:handle_groupchat_to_room(origin, stanza)
817 local from = stanza.attr.from;
818 local occupant = self:get_occupant_by_real_jid(from);
819 if module:fire_event("muc-occupant-groupchat", {
820 room = self; origin = origin; stanza = stanza; from = from; occupant = occupant;
821 }) then return true; end
822 stanza.attr.from = occupant.nick;
823 self:broadcast_message(stanza);
824 stanza.attr.from = from;
829 module:hook("muc-occupant-groupchat", function(event)
830 local role_rank = valid_roles[event.occupant and event.occupant.role or "none"];
831 if role_rank <= valid_roles.none then
832 event.origin.send(st.error_reply(event.stanza, "cancel", "not-acceptable"));
834 elseif role_rank <= valid_roles.visitor then
835 event.origin.send(st.error_reply(event.stanza, "auth", "forbidden"));
840 -- hack - some buggy clients send presence updates to the room rather than their nick
841 function room_mt:handle_presence_to_room(origin, stanza)
842 local current_nick = self:get_occupant_jid(stanza.attr.from);
845 local to = stanza.attr.to;
846 stanza.attr.to = current_nick;
847 handled = self:handle_presence_to_occupant(origin, stanza);
853 -- Need visitor role or higher to invite
854 module:hook("muc-pre-invite", function(event)
855 local room, stanza = event.room, event.stanza;
856 local _from, _to = stanza.attr.from, stanza.attr.to;
857 local inviter = room:get_occupant_by_real_jid(_from);
858 local role = inviter and inviter.role or room:get_default_role(room:get_affiliation(_from));
859 if valid_roles[role or "none"] <= valid_roles.visitor then
860 event.origin.send(st.error_reply(stanza, "auth", "forbidden"));
865 function room_mt:handle_mediated_invite(origin, stanza)
866 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
867 local invitee = jid_prep(payload.attr.to);
869 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
871 elseif module:fire_event("muc-pre-invite", {room = self, origin = origin, stanza = stanza}) then
874 local invite = muc_util.filter_muc_x(st.clone(stanza));
875 invite.attr.from = self.jid;
876 invite.attr.to = invitee;
877 invite:tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
878 :tag('invite', {from = stanza.attr.from;})
879 :tag('reason'):text(payload:get_child_text("reason")):up()
882 if not module:fire_event("muc-invite", {room = self, stanza = invite, origin = origin, incoming = stanza}) then
883 self:route_stanza(invite);
888 -- COMPAT: Some older clients expect this
889 module:hook("muc-invite", function(event)
890 local room, stanza = event.room, event.stanza;
891 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
892 local reason = invite:get_child_text("reason");
893 stanza:tag('x', {xmlns = "jabber:x:conference"; jid = room.jid;})
898 -- Add a plain message for clients which don't support invites
899 module:hook("muc-invite", function(event)
900 local room, stanza = event.room, event.stanza;
901 if not stanza:get_child("body") then
902 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
903 local reason = invite:get_child_text("reason") or "";
905 :text(invite.attr.from.." invited you to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
910 function room_mt:handle_mediated_decline(origin, stanza)
911 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
912 local declinee = jid_prep(payload.attr.to);
914 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
916 elseif module:fire_event("muc-pre-decline", {room = self, origin = origin, stanza = stanza}) then
919 local decline = muc_util.filter_muc_x(st.clone(stanza));
920 decline.attr.from = self.jid;
921 decline.attr.to = declinee;
922 decline:tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
923 :tag("decline", {from = stanza.attr.from})
924 :tag("reason"):text(payload:get_child_text("reason")):up()
927 if not module:fire_event("muc-decline", {room = self, stanza = decline, origin = origin, incoming = stanza}) then
928 local declinee = decline.attr.to; -- re-fetch, in case event modified it
930 if jid_bare(declinee) == self.jid then -- declinee jid is already an in-room jid
931 occupant = self:get_occupant_by_nick(declinee);
934 self:route_to_occupant(occupant, decline);
936 self:route_stanza(decline);
942 -- Add a plain message for clients which don't support declines
943 module:hook("muc-decline", function(event)
944 local room, stanza = event.room, event.stanza;
945 if not stanza:get_child("body") then
946 local decline = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
947 local reason = decline:get_child_text("reason") or "";
949 :text(decline.attr.from.." declined your invite to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
954 function room_mt:handle_message_to_room(origin, stanza)
955 local type = stanza.attr.type;
956 if type == "groupchat" then
957 return self:handle_groupchat_to_room(origin, stanza)
958 elseif type == "error" and is_kickable_error(stanza) then
959 return self:handle_kickable(origin, stanza)
960 elseif type == nil then
961 local x = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
963 local payload = x.tags[1];
964 if payload == nil then
966 elseif payload.name == "invite" and payload.attr.to then
967 return self:handle_mediated_invite(origin, stanza)
968 elseif payload.name == "decline" and payload.attr.to then
969 return self:handle_mediated_decline(origin, stanza)
971 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
977 function room_mt:route_stanza(stanza)
981 function room_mt:get_affiliation(jid)
982 local node, host, resource = jid_split(jid);
983 local bare = node and node.."@"..host or host;
984 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
985 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
989 -- Iterates over jid, affiliation pairs
990 function room_mt:each_affiliation(with_affiliation)
991 if not with_affiliation then
992 return pairs(self._affiliations);
994 return function(_affiliations, jid)
996 repeat -- Iterate until we get a match
997 jid, affiliation = next(_affiliations, jid);
998 until jid == nil or affiliation == with_affiliation
999 return jid, affiliation;
1000 end, self._affiliations, nil
1004 function room_mt:set_affiliation(actor, jid, affiliation, reason)
1005 if not actor then return nil, "modify", "not-acceptable"; end;
1007 local node, host, resource = jid_split(jid);
1008 if not host then return nil, "modify", "not-acceptable"; end
1009 jid = jid_join(node, host); -- Bare
1010 local is_host_only = node == nil;
1012 if valid_affiliations[affiliation or "none"] == nil then
1013 return nil, "modify", "not-acceptable";
1015 affiliation = affiliation ~= "none" and affiliation or nil; -- coerces `affiliation == false` to `nil`
1017 local target_affiliation = self._affiliations[jid]; -- Raw; don't want to check against host
1018 local is_downgrade = valid_affiliations[target_affiliation or "none"] > valid_affiliations[affiliation or "none"];
1020 if actor == true then
1021 actor = nil -- So we can pass it safely to 'publicise_occupant_status' below
1023 local actor_affiliation = self:get_affiliation(actor);
1024 if actor_affiliation == "owner" then
1025 if jid_bare(actor) == jid then -- self change
1026 -- need at least one owner
1027 local is_last = true;
1028 for j in self:each_affiliation("owner") do
1029 if j ~= jid then is_last = false; break; end
1032 return nil, "cancel", "conflict";
1035 -- owners can do anything else
1036 elseif affiliation == "owner" or affiliation == "admin"
1037 or actor_affiliation ~= "admin"
1038 or target_affiliation == "owner" or target_affiliation == "admin" then
1039 -- Can't demote owners or other admins
1040 return nil, "cancel", "not-allowed";
1044 -- Set in 'database'
1045 self._affiliations[jid] = affiliation;
1048 local role = self:get_default_role(affiliation);
1049 local role_rank = valid_roles[role or "none"];
1050 local occupants_updated = {}; -- Filled with old roles
1051 for nick, occupant in self:each_occupant() do
1052 if occupant.bare_jid == jid or (
1053 -- Outcast can be by host.
1054 is_host_only and affiliation == "outcast" and select(2, jid_split(occupant.bare_jid)) == host
1056 -- need to publcize in all cases; as affiliation in <item/> has changed.
1057 occupants_updated[occupant] = occupant.role;
1058 if occupant.role ~= role and (
1060 valid_roles[occupant.role or "none"] < role_rank -- upgrade
1062 occupant.role = role;
1063 self:save_occupant(occupant);
1068 -- Tell the room of the new occupant affiliations+roles
1069 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1070 if not role then -- getting kicked
1071 if affiliation == "outcast" then
1072 x:tag("status", {code="301"}):up(); -- banned
1074 x:tag("status", {code="321"}):up(); -- affiliation change
1077 local is_semi_anonymous = self:get_whois() == "moderators";
1078 for occupant, old_role in pairs(occupants_updated) do
1079 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1080 if occupant.role == nil then
1081 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
1082 elseif is_semi_anonymous and
1083 (old_role == "moderator" and occupant.role ~= "moderator") or
1084 (old_role ~= "moderator" and occupant.role == "moderator") then -- Has gained or lost moderator status
1085 -- Send everyone else's presences (as jid visibility has changed)
1086 for real_jid in occupant:each_session() do
1087 self:send_occupant_list(real_jid, function(occupant_jid, occupant)
1088 return occupant.bare_jid ~= jid;
1094 if self.save then self:save(); end
1096 module:fire_event("muc-set-affiliation", {
1100 affiliation = affiliation or "none";
1102 previous_affiliation = target_affiliation;
1103 in_room = next(occupants_updated) ~= nil;
1109 function room_mt:get_role(nick)
1110 local occupant = self:get_occupant_by_nick(nick);
1111 return occupant and occupant.role or nil;
1114 function room_mt:set_role(actor, occupant_jid, role, reason)
1115 if not actor then return nil, "modify", "not-acceptable"; end
1117 local occupant = self:get_occupant_by_nick(occupant_jid);
1118 if not occupant then return nil, "modify", "not-acceptable"; end
1120 if valid_roles[role or "none"] == nil then
1121 return nil, "modify", "not-acceptable";
1123 role = role ~= "none" and role or nil; -- coerces `role == false` to `nil`
1125 if actor == true then
1126 actor = nil -- So we can pass it safely to 'publicise_occupant_status' below
1128 -- Can't do anything to other owners or admins
1129 local occupant_affiliation = self:get_affiliation(occupant.bare_jid);
1130 if occupant_affiliation == "owner" and occupant_affiliation == "admin" then
1131 return nil, "cancel", "not-allowed";
1134 -- If you are trying to give or take moderator role you need to be an owner or admin
1135 if occupant.role == "moderator" or role == "moderator" then
1136 local actor_affiliation = self:get_affiliation(actor);
1137 if actor_affiliation ~= "owner" and actor_affiliation ~= "admin" then
1138 return nil, "cancel", "not-allowed";
1142 -- Need to be in the room and a moderator
1143 local actor_occupant = self:get_occupant_by_real_jid(actor);
1144 if not actor_occupant or actor_occupant.role ~= "moderator" then
1145 return nil, "cancel", "not-allowed";
1149 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1151 x:tag("status", {code = "307"}):up();
1153 occupant.role = role;
1154 self:save_occupant(occupant);
1155 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1157 module:fire_event("muc-occupant-left", {room = self; nick = occupant.nick; occupant = occupant;});
1162 local affiliation_notify = module:require "muc/affiliation_notify";
1164 local name = module:require "muc/name";
1165 room_mt.get_name = name.get;
1166 room_mt.set_name = name.set;
1168 local description = module:require "muc/description";
1169 room_mt.get_description = description.get;
1170 room_mt.set_description = description.set;
1172 local hidden = module:require "muc/hidden";
1173 room_mt.get_hidden = hidden.get;
1174 room_mt.set_hidden = hidden.set;
1175 function room_mt:get_public()
1176 return not self:get_hidden();
1178 function room_mt:set_public(public)
1179 return self:set_hidden(not public);
1182 local password = module:require "muc/password";
1183 room_mt.get_password = password.get;
1184 room_mt.set_password = password.set;
1186 local whois = module:require "muc/whois";
1187 room_mt.get_whois = whois.get;
1188 room_mt.set_whois = whois.set;
1190 local members_only = module:require "muc/members_only";
1191 room_mt.get_members_only = members_only.get;
1192 room_mt.set_members_only = members_only.set;
1194 local moderated = module:require "muc/moderated";
1195 room_mt.get_moderated = moderated.get;
1196 room_mt.set_moderated = moderated.set;
1198 local persistent = module:require "muc/persistent";
1199 room_mt.get_persistent = persistent.get;
1200 room_mt.set_persistent = persistent.set;
1202 local subject = module:require "muc/subject";
1203 room_mt.get_changesubject = subject.get_changesubject;
1204 room_mt.set_changesubject = subject.set_changesubject;
1205 room_mt.get_subject = subject.get;
1206 room_mt.set_subject = subject.set;
1207 room_mt.send_subject = subject.send;
1209 local history = module:require "muc/history";
1210 room_mt.send_history = history.send;
1211 room_mt.get_historylength = history.get_length;
1212 room_mt.set_historylength = history.set_length;
1214 local _M = {}; -- module "muc"
1216 function _M.new_room(jid, config)
1217 return setmetatable({
1227 _M.room_mt = room_mt;