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.none then
57 --- Occupant functions
58 function room_mt:new_occupant(bare_real_jid, nick)
59 local occupant = occupant_lib.new(bare_real_jid, nick);
60 local affiliation = self:get_affiliation(bare_real_jid);
61 occupant.role = self:get_default_role(affiliation);
65 function room_mt:get_occupant_by_nick(nick)
66 local occupant = self._occupants[nick];
67 if occupant == nil then return nil end
68 return occupant_lib.copy(occupant);
72 local function next_copied_occupant(occupants, occupant_jid)
73 local next_occupant_jid, raw_occupant = next(occupants, occupant_jid);
74 if next_occupant_jid == nil then return nil end
75 return next_occupant_jid, occupant_lib.copy(raw_occupant);
77 function room_mt:each_occupant(read_only)
78 return next_copied_occupant, self._occupants, nil;
82 function room_mt:has_occupant()
83 return next(self._occupants, nil) ~= nil
86 function room_mt:get_occupant_by_real_jid(real_jid)
87 local occupant_jid = self:get_occupant_jid(real_jid);
88 if occupant_jid == nil then return nil end
89 return self:get_occupant_by_nick(occupant_jid);
92 function room_mt:save_occupant(occupant)
93 occupant = occupant_lib.copy(occupant); -- So that occupant can be modified more
94 local id = occupant.nick
96 -- Need to maintain _jid_nick secondary index
97 local old_occupant = self._occupants[id];
99 for real_jid in pairs(old_occupant.sessions) do
100 self._jid_nick[real_jid] = nil;
104 local has_live_session = false
105 if occupant.role ~= nil then
106 for real_jid, presence in occupant:each_session() do
107 if presence.attr.type == nil then
108 has_live_session = true
109 self._jid_nick[real_jid] = occupant.nick;
112 if not has_live_session then
113 -- Has no live sessions left; they have left the room.
117 if not has_live_session then
120 self._occupants[id] = occupant
123 function room_mt:route_to_occupant(occupant, stanza)
124 local to = stanza.attr.to;
125 for jid, pr in occupant:each_session() do
126 if pr.attr.type ~= "unavailable" then
127 stanza.attr.to = jid;
128 self:route_stanza(stanza);
134 -- actor is the attribute table
135 local function add_item(x, affiliation, role, jid, nick, actor, reason)
136 x:tag("item", {affiliation = affiliation; role = role; jid = jid; nick = nick;})
138 x:tag("actor", actor):up()
141 x:tag("reason"):text(reason):up()
147 -- actor is (real) jid
148 function room_mt:build_item_list(occupant, x, is_anonymous, nick, actor, reason)
149 local affiliation = self:get_affiliation(occupant.bare_jid) or "none";
150 local role = occupant.role or "none";
153 actor_attr = {nick = select(3,jid_split(self:get_occupant_jid(actor)))};
156 add_item(x, affiliation, role, nil, nick, actor_attr, reason);
159 actor_attr.jid = actor;
161 for real_jid, session in occupant:each_session() do
162 add_item(x, affiliation, role, real_jid, nick, actor_attr, reason);
168 function room_mt:broadcast_message(stanza)
169 module:fire_event("muc-broadcast-message", {room = self, stanza = stanza});
170 self:broadcast(stanza);
173 -- Broadcast a stanza to all occupants in the room.
174 -- optionally checks conditional called with (nick, occupant)
175 function room_mt:broadcast(stanza, cond_func)
176 for nick, occupant in self:each_occupant() do
177 if cond_func == nil or cond_func(nick, occupant) then
178 self:route_to_occupant(occupant, stanza)
183 local function can_see_real_jids(whois, occupant)
184 if whois == "anyone" then
186 elseif whois == "moderators" then
187 return valid_roles[occupant.role or "none"] >= valid_roles.moderator;
191 local function get_base_presence(occupant)
192 if occupant.role ~= nil then
193 -- Try to use main jid's presence
194 local pr = occupant:get_presence();
199 return st.presence {from = occupant.nick; type = "unavailable";};
202 -- Broadcasts an occupant's presence to the whole room
203 -- Takes the x element that goes into the stanzas
204 function room_mt:publicise_occupant_status(occupant, base_x, nick, actor, reason)
205 -- Build real jid and (optionally) occupant jid template presences
206 local function get_presence(is_anonymous)
207 local x = st.clone(base_x);
208 self:build_item_list(occupant, x, is_anonymous, nick, actor, reason);
209 return get_base_presence(occupant):add_child(x), x;
211 local full_p, full_x = get_presence(false);
212 local anon_p, anon_x;
213 local function get_anon_p()
214 if anon_p == nil then
215 anon_p, anon_x = get_presence(true);
217 return anon_p, anon_x;
220 local whois = self:get_whois();
223 for nick, n_occupant in self:each_occupant() do
224 if nick ~= occupant.nick then
226 if can_see_real_jids(whois, occupant) or occupant.bare_jid == n_occupant.bare_jid then
231 self:route_to_occupant(n_occupant, pr);
235 -- Presences for occupant itself
236 full_x:tag("status", {code = "110";}):up();
237 if occupant.role == nil then
238 -- They get an unavailable
239 self:route_to_occupant(occupant, full_p);
241 -- use their own presences as templates
242 for full_jid, pr in occupant:each_session() do
244 pr.attr.to = full_jid;
245 -- You can always see your own full jids
246 pr:add_child(full_x);
247 self:route_stanza(pr);
252 function room_mt:send_occupant_list(to, filter)
253 local to_bare = jid_bare(to);
254 local is_anonymous = true;
255 local whois = self:get_whois();
256 if whois ~= "anyone" then
257 local affiliation = self:get_affiliation(to);
258 if affiliation ~= "admin" and affiliation ~= "owner" then
259 local occupant = self:get_occupant_by_real_jid(to);
260 if not occupant or can_see_real_jids(whois, occupant) then
261 is_anonymous = false;
265 for occupant_jid, occupant in self:each_occupant() do
266 if filter == nil or filter(occupant_jid, occupant) then
267 local x = st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
268 self:build_item_list(occupant, x, is_anonymous and to_bare ~= occupant.bare_jid); -- can always see your own jids
269 local pres = st.clone(occupant:get_presence());
272 self:route_stanza(pres);
277 function room_mt:get_disco_info(stanza)
278 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#info");
279 local form = dataform.new {
280 { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" };
282 module:fire_event("muc-disco#info", {room = self; reply = reply; form = form;});
283 reply:add_child(form:form(nil, "result"));
286 module:hook("muc-disco#info", function(event)
287 event.reply:tag("feature", {var = "http://jabber.org/protocol/muc"}):up();
289 module:hook("muc-disco#info", function(event)
290 local count = iterators.count(event.room:each_occupant());
291 table.insert(event.form, { name = "muc#roominfo_occupants", label = "Number of occupants", value = tostring(count) });
294 function room_mt:get_disco_items(stanza)
295 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
296 for room_jid in self:each_occupant() do
297 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
302 function room_mt:handle_kickable(origin, stanza)
303 local real_jid = stanza.attr.from;
304 local occupant = self:get_occupant_by_real_jid(real_jid);
305 if occupant == nil then return nil; end
306 local type, condition, text = stanza:get_error();
307 local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
309 error_message = error_message..": "..text;
311 occupant:set_session(real_jid, st.presence({type="unavailable"})
312 :tag('status'):text(error_message));
313 self:save_occupant(occupant);
314 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
315 :tag("status", {code = "307"})
316 self:publicise_occupant_status(occupant, x);
320 -- Give the room creator owner affiliation
321 module:hook("muc-room-pre-create", function(event)
322 event.room:set_affiliation(true, jid_bare(event.stanza.attr.from), "owner");
325 -- check if user is banned
326 module:hook("muc-occupant-pre-join", function(event)
327 local room, stanza = event.room, event.stanza;
328 local affiliation = room:get_affiliation(stanza.attr.from);
329 if affiliation == "outcast" then
330 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
331 reply.tags[1].attr.code = "403";
332 event.origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
337 function room_mt:handle_presence_to_occupant(origin, stanza)
338 local type = stanza.attr.type;
339 if type == "error" then -- error, kick em out!
340 return self:handle_kickable(origin, stanza)
341 elseif type == nil or type == "unavailable" then
342 local real_jid = stanza.attr.from;
343 local bare_jid = jid_bare(real_jid);
344 local orig_occupant, dest_occupant;
345 local is_new_room = next(self._affiliations) == nil;
347 if type == "unavailable" then return true; end -- Unavailable from someone not in the room
348 if module:fire_event("muc-room-pre-create", {
352 }) then return true; end
354 orig_occupant = self:get_occupant_by_real_jid(real_jid);
355 if type == "unavailable" and orig_occupant == nil then return true; end -- Unavailable from someone not in the room
357 local is_first_dest_session;
358 if type == "unavailable" then
359 -- dest_occupant = nil
360 elseif orig_occupant and orig_occupant.nick == stanza.attr.to then -- Just a presence update
361 log("debug", "presence update for %s from session %s", orig_occupant.nick, real_jid);
362 dest_occupant = orig_occupant;
364 local dest_jid = stanza.attr.to;
365 dest_occupant = self:get_occupant_by_nick(dest_jid);
366 if dest_occupant == nil then
367 log("debug", "no occupant found for %s; creating new occupant object for %s", dest_jid, real_jid);
368 is_first_dest_session = true;
369 dest_occupant = self:new_occupant(bare_jid, dest_jid);
371 is_first_dest_session = false;
374 local is_last_orig_session;
375 if orig_occupant ~= nil then
376 -- Is there are least 2 sessions?
377 local iter, ob, last = orig_occupant:each_session();
378 is_last_orig_session = iter(ob, iter(ob, last)) == nil;
381 local event, event_name = {
385 is_first_session = is_first_dest_session;
386 is_last_session = is_last_orig_session;
388 if orig_occupant == nil then
389 event_name = "muc-occupant-pre-join";
390 event.is_new_room = is_new_room;
391 elseif dest_occupant == nil then
392 event_name = "muc-occupant-pre-leave";
394 event_name = "muc-occupant-pre-change";
396 if module:fire_event(event_name, event) then return true; end
398 -- Check for nick conflicts
399 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
400 log("debug", "%s couldn't join due to nick conflict: %s", real_jid, dest_occupant.nick);
401 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
402 reply.tags[1].attr.code = "409";
403 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
407 -- Send presence stanza about original occupant
408 if orig_occupant ~= nil and orig_occupant ~= dest_occupant then
409 local orig_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
411 if dest_occupant == nil then -- Session is leaving
412 log("debug", "session %s is leaving occupant %s", real_jid, orig_occupant.nick);
413 if is_last_orig_session then
414 orig_occupant.role = nil;
416 orig_occupant:set_session(real_jid, stanza);
418 log("debug", "session %s is changing from occupant %s to %s", real_jid, orig_occupant.nick, dest_occupant.nick);
419 local generated_unavail = st.presence {from = orig_occupant.nick, to = real_jid, type = "unavailable"};
420 orig_occupant:set_session(real_jid, generated_unavail);
421 dest_nick = select(3, jid_split(dest_occupant.nick));
422 if not is_first_dest_session then -- User is swapping into another pre-existing session
423 log("debug", "session %s is swapping into multisession %s, showing it leave.", real_jid, dest_occupant.nick);
424 -- Show the other session leaving
425 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
426 :tag("status"):text("you are joining pre-existing session " .. dest_nick):up();
427 add_item(x, self:get_affiliation(bare_jid), "none");
428 local pr = st.presence{from = dest_occupant.nick, to = real_jid, type = "unavailable"}
430 self:route_stanza(pr);
432 if is_first_dest_session and is_last_orig_session then -- Normal nick change
433 log("debug", "no sessions in %s left; publically marking as nick change", orig_occupant.nick);
434 orig_x:tag("status", {code = "303";}):up();
435 else -- The session itself always needs to see a nick change
436 -- don't want to get our old nick's available presence,
437 -- so remove our session from there, and manually generate an unavailable
438 orig_occupant:remove_session(real_jid);
439 log("debug", "generating nick change for %s", real_jid);
440 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
441 -- self:build_item_list(orig_occupant, x, false, dest_nick); -- COMPAT: clients get confused if they see other items besides their own
442 add_item(x, self:get_affiliation(bare_jid), orig_occupant.role, real_jid, dest_nick);
443 x:tag("status", {code = "303";}):up();
444 x:tag("status", {code = "110";}):up();
445 self:route_stanza(generated_unavail:add_child(x));
446 dest_nick = nil; -- set dest_nick to nil; so general populance doesn't see it for whole orig_occupant
449 self:save_occupant(orig_occupant);
450 self:publicise_occupant_status(orig_occupant, orig_x, dest_nick);
452 if is_last_orig_session then
453 module:fire_event("muc-occupant-left", {room = self; nick = orig_occupant.nick;});
457 if dest_occupant ~= nil then
458 dest_occupant:set_session(real_jid, stanza);
459 local dest_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
461 dest_x:tag("status", {code = "201"}):up();
463 if orig_occupant == nil and self:get_whois() == "anyone" then
464 dest_x:tag("status", {code = "100"}):up();
466 self:save_occupant(dest_occupant);
468 if orig_occupant == nil then
469 -- Send occupant list to newly joined user
470 self:send_occupant_list(real_jid, function(nick, occupant)
471 -- Don't include self
472 return occupant:get_presence(real_jid) == nil;
475 self:publicise_occupant_status(dest_occupant, dest_x);
477 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
478 log("debug", "session %s split nicks; showing %s rejoining", real_jid, orig_occupant.nick);
479 -- Show the original nick joining again
480 local pr = st.clone(orig_occupant:get_presence());
481 pr.attr.to = real_jid;
482 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
483 self:build_item_list(orig_occupant, x, false);
484 -- TODO: new status code to inform client this was the multi-session it left?
486 self:route_stanza(pr);
489 if orig_occupant == nil and is_first_dest_session then
490 module:fire_event("muc-occupant-joined", {room = self; nick = dest_occupant.nick; stanza = stanza;});
493 elseif type ~= 'result' then -- bad type
494 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
495 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
501 function room_mt:handle_iq_to_occupant(origin, stanza)
502 local from, to = stanza.attr.from, stanza.attr.to;
503 local type = stanza.attr.type;
504 local id = stanza.attr.id;
505 local occupant = self:get_occupant_by_nick(to);
506 if (type == "error" or type == "result") then
507 do -- deconstruct_stanza_id
508 if not occupant then return nil; end
509 local from_jid, id, to_jid_hash = (base64.decode(stanza.attr.id) or ""):match("^(.+)%z(.*)%z(.+)$");
510 if not(from == from_jid or from == jid_bare(from_jid)) then return nil; end
511 local from_occupant_jid = self:get_occupant_jid(from_jid);
512 if from_occupant_jid == nil then return nil; end
514 for to_jid in occupant:each_session() do
515 if md5(to_jid) == to_jid_hash then
516 session_jid = to_jid;
520 if session_jid == nil then return nil; end
521 stanza.attr.from, stanza.attr.to, stanza.attr.id = from_jid, session_jid, id;
523 log("debug", "%s sent private iq stanza to %s (%s)", from, to, stanza.attr.to);
524 self:route_stanza(stanza);
525 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
527 else -- Type is "get" or "set"
528 local current_nick = self:get_occupant_jid(from);
529 if not current_nick then
530 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
533 if not occupant then -- recipient not in room
534 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
537 do -- construct_stanza_id
538 stanza.attr.id = base64.encode(occupant.jid.."\0"..stanza.attr.id.."\0"..md5(from));
540 stanza.attr.from, stanza.attr.to = current_nick, occupant.jid;
541 log("debug", "%s sent private iq stanza to %s (%s)", from, to, occupant.jid);
542 if stanza.tags[1].attr.xmlns == 'vcard-temp' then
543 stanza.attr.to = jid_bare(stanza.attr.to);
545 self:route_stanza(stanza);
546 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
551 function room_mt:handle_message_to_occupant(origin, stanza)
552 local from, to = stanza.attr.from, stanza.attr.to;
553 local current_nick = self:get_occupant_jid(from);
554 local type = stanza.attr.type;
555 if not current_nick then -- not in room
556 if type ~= "error" then
557 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
561 if type == "groupchat" then -- groupchat messages not allowed in PM
562 origin.send(st.error_reply(stanza, "modify", "bad-request"));
564 elseif type == "error" and is_kickable_error(stanza) then
565 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
566 return self:handle_kickable(origin, stanza); -- send unavailable
569 local o_data = self:get_occupant_by_nick(to);
571 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
574 log("debug", "%s sent private message stanza to %s (%s)", from, to, o_data.jid);
575 stanza:tag("x", { xmlns = "http://jabber.org/protocol/muc#user" }):up();
576 stanza.attr.from = current_nick;
577 self:route_to_occupant(o_data, stanza)
578 -- TODO: Remove x tag?
579 stanza.attr.from = from;
583 function room_mt:send_form(origin, stanza)
584 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
585 :add_child(self:get_form_layout(stanza.attr.from):form())
589 function room_mt:get_form_layout(actor)
590 local form = dataform.new({
591 title = "Configuration for "..self.jid,
592 instructions = "Complete and submit this form to configure the room.",
596 value = 'http://jabber.org/protocol/muc#roomconfig'
599 return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
602 function room_mt:process_form(origin, stanza)
603 local form = stanza.tags[1]:get_child("x", "jabber:x:data");
604 if form.attr.type == "cancel" then
605 origin.send(st.reply(stanza));
606 elseif form.attr.type == "submit" then
607 local fields = self:get_form_layout(stanza.attr.from):data(form);
608 if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then
609 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration"));
613 local event = {room = self; origin = origin; stanza = stanza; fields = fields; status_codes = {};};
614 function event.update_option(name, field, allowed)
615 local new = fields[field];
616 if new == nil then return; end
617 if allowed and not allowed[new] then return; end
618 if new == self["get_"..name](self) then return; end
619 event.status_codes["104"] = true;
620 self["set_"..name](self, new);
623 module:fire_event("muc-config-submitted", event);
625 if self.save then self:save(true); end
626 origin.send(st.reply(stanza));
628 if next(event.status_codes) then
629 local msg = st.message({type='groupchat', from=self.jid})
630 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
631 for code in pairs(event.status_codes) do
632 msg:tag("status", {code = code;}):up();
635 self:broadcast_message(msg);
638 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form"));
643 -- Removes everyone from the room
644 function room_mt:clear(x)
645 x = x or st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
646 local occupants_updated = {};
647 for nick, occupant in self:each_occupant() do
649 self:save_occupant(occupant);
650 occupants_updated[occupant] = true;
652 for occupant in pairs(occupants_updated) do
653 self:publicise_occupant_status(occupant, x);
654 module:fire_event("muc-occupant-left", { room = self; nick = occupant.nick; });
658 function room_mt:destroy(newjid, reason, password)
659 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
660 :tag("item", { affiliation='none', role='none' }):up()
661 :tag("destroy", {jid=newjid});
662 if reason then x:tag("reason"):text(reason):up(); end
663 if password then x:tag("password"):text(password):up(); end
666 module:fire_event("muc-room-destroyed", { room = self });
669 function room_mt:handle_disco_info_get_query(origin, stanza)
670 origin.send(self:get_disco_info(stanza));
674 function room_mt:handle_disco_items_get_query(origin, stanza)
675 origin.send(self:get_disco_items(stanza));
679 function room_mt:handle_admin_query_set_command(origin, stanza)
680 local item = stanza.tags[1].tags[1];
681 if item.attr.jid then -- Validate provided JID
682 item.attr.jid = jid_prep(item.attr.jid);
683 if not item.attr.jid then
684 origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
688 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
689 local occupant = self:get_occupant_by_nick(self.jid.."/"..item.attr.nick);
690 if occupant then item.attr.jid = occupant.jid; end
691 elseif not item.attr.nick and item.attr.jid then
692 local nick = self:get_occupant_jid(item.attr.jid);
693 if nick then item.attr.nick = select(3, jid_split(nick)); end
695 local actor = stanza.attr.from;
696 local reason = item:get_child_text("reason");
697 local success, errtype, err
698 if item.attr.affiliation and item.attr.jid and not item.attr.role then
699 success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, reason);
700 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
701 success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, reason);
703 success, errtype, err = nil, "cancel", "bad-request";
705 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
706 origin.send(st.reply(stanza));
710 function room_mt:handle_admin_query_get_command(origin, stanza)
711 local actor = stanza.attr.from;
712 local affiliation = self:get_affiliation(actor);
713 local item = stanza.tags[1].tags[1];
714 local _aff = item.attr.affiliation;
715 local _rol = item.attr.role;
716 if _aff and not _rol then
717 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
718 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
719 for jid, affiliation in pairs(self._affiliations) do
720 if affiliation == _aff then
721 reply:tag("item", {affiliation = _aff, jid = jid}):up();
727 origin.send(st.error_reply(stanza, "auth", "forbidden"));
730 elseif _rol and not _aff then
731 local role = self:get_role(self:get_occupant_jid(actor)) or self:get_default_role(affiliation);
732 if valid_roles[role or "none"] >= valid_roles.moderator then
733 if _rol == "none" then _rol = nil; end
734 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
735 -- TODO: whois check here? (though fully anonymous rooms are not supported)
736 for occupant_jid, occupant in self:each_occupant() do
737 if occupant.role == _rol then
738 local nick = select(3,jid_split(occupant_jid));
739 self:build_item_list(occupant, reply, false, nick);
742 origin.send(reply:up());
745 origin.send(st.error_reply(stanza, "auth", "forbidden"));
749 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
754 function room_mt:handle_owner_query_get_to_room(origin, stanza)
755 if self:get_affiliation(stanza.attr.from) ~= "owner" then
756 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
760 self:send_form(origin, stanza);
763 function room_mt:handle_owner_query_set_to_room(origin, stanza)
764 if self:get_affiliation(stanza.attr.from) ~= "owner" then
765 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
769 local child = stanza.tags[1].tags[1];
771 origin.send(st.error_reply(stanza, "modify", "bad-request"));
773 elseif child.name == "destroy" then
774 local newjid = child.attr.jid;
775 local reason = child:get_child_text("reason");
776 local password = child:get_child_text("password");
777 self:destroy(newjid, reason, password);
778 origin.send(st.reply(stanza));
780 elseif child.name == "x" and child.attr.xmlns == "jabber:x:data" then
781 return self:process_form(origin, stanza);
783 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
788 function room_mt:handle_groupchat_to_room(origin, stanza)
789 -- Prosody has made the decision that messages with <subject/> are exclusively subject changes
790 -- e.g. body will be ignored; even if the subject change was not allowed
791 if stanza:get_child("subject") then
792 return module:fire_event("muc-subject-change", {room = self, origin = origin, stanza = stanza});
794 local from = stanza.attr.from;
795 local occupant = self:get_occupant_by_real_jid(from);
796 if not occupant then -- not in room
797 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
799 elseif occupant.role == "visitor" then
800 origin.send(st.error_reply(stanza, "auth", "forbidden"));
803 stanza.attr.from = occupant.nick;
804 self:broadcast_message(stanza);
805 stanza.attr.from = from;
809 -- hack - some buggy clients send presence updates to the room rather than their nick
810 function room_mt:handle_presence_to_room(origin, stanza)
811 local current_nick = self:get_occupant_jid(stanza.attr.from);
814 local to = stanza.attr.to;
815 stanza.attr.to = current_nick;
816 handled = self:handle_presence_to_occupant(origin, stanza);
822 -- Need visitor role or higher to invite
823 module:hook("muc-pre-invite", function(event)
824 local room, stanza = event.room, event.stanza;
825 local _from, _to = stanza.attr.from, stanza.attr.to;
826 local inviter = room:get_occupant_by_real_jid(_from);
827 local role = inviter and inviter.role or room:get_default_role(room:get_affiliation(_from));
828 if valid_roles[role or "none"] <= valid_roles.visitor then
829 event.origin.send(st.error_reply(stanza, "auth", "forbidden"));
834 function room_mt:handle_mediated_invite(origin, stanza)
835 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
836 local invitee = jid_prep(payload.attr.to);
838 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
840 elseif module:fire_event("muc-pre-invite", {room = self, origin = origin, stanza = stanza}) then
843 local invite = st.message({from = self.jid, to = invitee, id = stanza.attr.id})
844 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
845 :tag('invite', {from = stanza.attr.from;})
846 :tag('reason'):text(payload:get_child_text("reason")):up()
849 if not module:fire_event("muc-invite", {room = self, stanza = invite, origin = origin, incoming = stanza}) then
850 self:route_stanza(invite);
855 -- COMPAT: Some older clients expect this
856 module:hook("muc-invite", function(event)
857 local room, stanza = event.room, event.stanza;
858 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
859 local reason = invite:get_child_text("reason");
860 stanza:tag('x', {xmlns = "jabber:x:conference"; jid = room.jid;})
865 -- Add a plain message for clients which don't support invites
866 module:hook("muc-invite", function(event)
867 local room, stanza = event.room, event.stanza;
868 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
869 local reason = invite:get_child_text("reason") or "";
871 :text(invite.attr.from.." invited you to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
875 function room_mt:handle_mediated_decline(origin, stanza)
876 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
877 local declinee = jid_prep(payload.attr.to);
879 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
881 elseif module:fire_event("muc-pre-decline", {room = self, origin = origin, stanza = stanza}) then
884 local decline = st.message({from = self.jid, to = declinee, id = stanza.attr.id})
885 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
886 :tag("decline", {from = stanza.attr.from})
887 :tag("reason"):text(payload:get_child_text("reason")):up()
890 if not module:fire_event("muc-decline", {room = self, stanza = decline, origin = origin, incoming = stanza}) then
891 local occupant = self:get_occupant_by_real_jid(decline.attr.to);
893 self:route_to_occupant(occupant, decline);
895 self:route_stanza(decline);
901 -- Add a plain message for clients which don't support declines
902 module:hook("muc-decline", function(event)
903 local room, stanza = event.room, event.stanza;
904 local decline = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
905 local reason = decline:get_child_text("reason") or "";
907 :text(decline.attr.from.." declined your invite to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
911 function room_mt:handle_message_to_room(origin, stanza)
912 local type = stanza.attr.type;
913 if type == "groupchat" then
914 return self:handle_groupchat_to_room(origin, stanza)
915 elseif type == "error" and is_kickable_error(stanza) then
916 return self:handle_kickable(origin, stanza)
917 elseif type == nil then
918 local x = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
920 local payload = x.tags[1];
921 if payload == nil then
923 elseif payload.name == "invite" and payload.attr.to then
924 return self:handle_mediated_invite(origin, stanza)
925 elseif payload.name == "decline" and payload.attr.to then
926 return self:handle_mediated_decline(origin, stanza)
928 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
934 function room_mt:route_stanza(stanza)
938 function room_mt:get_affiliation(jid)
939 local node, host, resource = jid_split(jid);
940 local bare = node and node.."@"..host or host;
941 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
942 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
946 function room_mt:set_affiliation(actor, jid, affiliation, reason)
947 if not actor then return nil, "modify", "not-acceptable"; end;
951 if valid_affiliations[affiliation or "none"] == nil then
952 return nil, "modify", "not-acceptable";
954 affiliation = affiliation ~= "none" and affiliation or nil; -- coerces `affiliation == false` to `nil`
956 local target_affiliation = self._affiliations[jid]; -- Raw; don't want to check against host
957 local is_downgrade = valid_affiliations[target_affiliation or "none"] > valid_affiliations[affiliation or "none"];
959 if actor ~= true then
960 local actor_bare = jid_bare(actor);
961 local actor_affiliation = self._affiliations[actor_bare];
962 if actor_affiliation == "owner" then
963 if actor_bare == jid then -- self change
964 -- need at least one owner
965 local is_last = true;
966 for j, aff in pairs(self._affiliations) do if j ~= jid and aff == "owner" then is_last = false; break; end end
968 return nil, "cancel", "conflict";
971 -- owners can do anything else
972 elseif affiliation == "owner" or affiliation == "admin"
973 or actor_affiliation ~= "admin"
974 or target_affiliation == "owner" or target_affiliation == "admin" then
975 -- Can't demote owners or other admins
976 return nil, "cancel", "not-allowed";
981 self._affiliations[jid] = affiliation;
984 local role = self:get_default_role(affiliation);
985 local role_rank = valid_roles[role or "none"];
986 local occupants_updated = {}; -- Filled with old roles
987 for nick, occupant in self:each_occupant() do
988 if occupant.bare_jid == jid then
989 -- need to publcize in all cases; as affiliation in <item/> has changed.
990 occupants_updated[occupant] = occupant.role;
991 if occupant.role ~= role and (
993 valid_roles[occupant.role or "none"] < role_rank -- upgrade
995 occupant.role = role;
996 self:save_occupant(occupant);
1001 -- Tell the room of the new occupant affiliations+roles
1002 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1003 if not role then -- getting kicked
1004 if affiliation == "outcast" then
1005 x:tag("status", {code="301"}):up(); -- banned
1007 x:tag("status", {code="321"}):up(); -- affiliation change
1010 local is_semi_anonymous = self:get_whois() == "moderators";
1011 for occupant, old_role in pairs(occupants_updated) do
1012 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1013 if is_semi_anonymous and
1014 (old_role == "moderator" and occupant.role ~= "moderator") or
1015 (old_role ~= "moderator" and occupant.role == "moderator") then -- Has gained or lost moderator status
1016 -- Send everyone else's presences (as jid visibility has changed)
1017 for real_jid in occupant:each_session() do
1018 self:send_occupant_list(real_jid, function(occupant_jid, occupant)
1019 return occupant.bare_jid ~= jid;
1025 if self.save then self:save(); end
1029 function room_mt:get_role(nick)
1030 local occupant = self:get_occupant_by_nick(nick);
1031 return occupant and occupant.role or nil;
1034 function room_mt:set_role(actor, occupant_jid, role, reason)
1035 if not actor then return nil, "modify", "not-acceptable"; end
1037 local occupant = self:get_occupant_by_nick(occupant_jid);
1038 if not occupant then return nil, "modify", "not-acceptable"; end
1040 if valid_roles[role or "none"] == nil then
1041 return nil, "modify", "not-acceptable";
1043 role = role ~= "none" and role or nil; -- coerces `role == false` to `nil`
1045 if actor ~= true then
1046 -- Can't do anything to other owners or admins
1047 local occupant_affiliation = self:get_affiliation(occupant.bare_jid);
1048 if occupant_affiliation == "owner" and occupant_affiliation == "admin" then
1049 return nil, "cancel", "not-allowed";
1052 -- If you are trying to give or take moderator role you need to be an owner or admin
1053 if occupant.role == "moderator" or role == "moderator" then
1054 local actor_affiliation = self:get_affiliation(actor);
1055 if actor_affiliation ~= "owner" and actor_affiliation ~= "admin" then
1056 return nil, "cancel", "not-allowed";
1060 -- Need to be in the room and a moderator
1061 local actor_occupant = self:get_occupant_by_real_jid(actor);
1062 if not actor_occupant or actor_occupant.role ~= "moderator" then
1063 return nil, "cancel", "not-allowed";
1067 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1069 x:tag("status", {code = "307"}):up();
1071 occupant.role = role;
1072 self:save_occupant(occupant);
1073 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1077 local name = module:require "muc/name";
1078 room_mt.get_name = name.get;
1079 room_mt.set_name = name.set;
1081 local description = module:require "muc/description";
1082 room_mt.get_description = description.get;
1083 room_mt.set_description = description.set;
1085 local hidden = module:require "muc/hidden";
1086 room_mt.get_hidden = hidden.get;
1087 room_mt.set_hidden = hidden.set;
1088 function room_mt:get_public()
1089 return not self:get_hidden();
1091 function room_mt:set_public(public)
1092 return self:set_hidden(not public);
1095 local password = module:require "muc/password";
1096 room_mt.get_password = password.get;
1097 room_mt.set_password = password.set;
1099 local whois = module:require "muc/whois";
1100 room_mt.get_whois = whois.get;
1101 room_mt.set_whois = whois.set;
1103 local members_only = module:require "muc/members_only";
1104 room_mt.get_members_only = members_only.get;
1105 room_mt.set_members_only = members_only.set;
1107 local moderated = module:require "muc/moderated";
1108 room_mt.get_moderated = moderated.get;
1109 room_mt.set_moderated = moderated.set;
1111 local persistent = module:require "muc/persistent";
1112 room_mt.get_persistent = persistent.get;
1113 room_mt.set_persistent = persistent.set;
1115 local subject = module:require "muc/subject";
1116 room_mt.get_changesubject = subject.get_changesubject;
1117 room_mt.set_changesubject = subject.set_changesubject;
1118 room_mt.get_subject = subject.get;
1119 room_mt.set_subject = subject.set;
1120 room_mt.send_subject = subject.send;
1122 local history = module:require "muc/history";
1123 room_mt.send_history = history.send;
1124 room_mt.get_historylength = history.get_length;
1125 room_mt.set_historylength = history.set_length;
1127 local _M = {}; -- module "muc"
1129 function _M.new_room(jid, config)
1130 return setmetatable({
1140 _M.room_mt = room_mt;