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 stanza.attr.to = jid;
127 self:route_stanza(stanza);
132 -- actor is the attribute table
133 local function add_item(x, affiliation, role, jid, nick, actor, reason)
134 x:tag("item", {affiliation = affiliation; role = role; jid = jid; nick = nick;})
136 x:tag("actor", actor):up()
139 x:tag("reason"):text(reason):up()
145 -- actor is (real) jid
146 function room_mt:build_item_list(occupant, x, is_anonymous, nick, actor, reason)
147 local affiliation = self:get_affiliation(occupant.bare_jid) or "none";
148 local role = occupant.role or "none";
151 actor_attr = {nick = select(3,jid_split(self:get_occupant_jid(actor)))};
154 add_item(x, affiliation, role, nil, nick, actor_attr, reason);
157 actor_attr.jid = actor;
159 for real_jid, session in occupant:each_session() do
160 add_item(x, affiliation, role, real_jid, nick, actor_attr, reason);
166 function room_mt:broadcast_message(stanza)
167 module:fire_event("muc-broadcast-message", {room = self, stanza = stanza});
168 self:broadcast(stanza);
171 -- Broadcast a stanza to all occupants in the room.
172 -- optionally checks conditional called with (nick, occupant)
173 function room_mt:broadcast(stanza, cond_func)
174 for nick, occupant in self:each_occupant() do
175 if cond_func == nil or cond_func(nick, occupant) then
176 self:route_to_occupant(occupant, stanza)
181 local function can_see_real_jids(whois, occupant)
182 if whois == "anyone" then
184 elseif whois == "moderators" then
185 return valid_roles[occupant.role or "none"] >= valid_roles.moderator;
189 local function get_base_presence(occupant)
190 if occupant.role ~= nil then
191 -- Try to use main jid's presence
192 local pr = occupant:get_presence();
197 return st.presence {from = occupant.nick; type = "unavailable";};
200 -- Broadcasts an occupant's presence to the whole room
201 -- Takes the x element that goes into the stanzas
202 function room_mt:publicise_occupant_status(occupant, base_x, nick, actor, reason)
203 -- Build real jid and (optionally) occupant jid template presences
204 local function get_presence(is_anonymous)
205 local x = st.clone(base_x);
206 self:build_item_list(occupant, x, is_anonymous, nick, actor, reason);
207 return get_base_presence(occupant):add_child(x), x;
209 local full_p, full_x = get_presence(false);
210 local anon_p, anon_x;
211 local function get_anon_p()
212 if anon_p == nil then
213 anon_p, anon_x = get_presence(true);
215 return anon_p, anon_x;
218 local whois = self:get_whois();
221 for nick, n_occupant in self:each_occupant() do
222 if nick ~= occupant.nick then
224 if can_see_real_jids(whois, occupant) or occupant.bare_jid == n_occupant.bare_jid then
229 self:route_to_occupant(n_occupant, pr);
233 -- Presences for occupant itself
234 full_x:tag("status", {code = "110";}):up();
235 if occupant.role == nil then
236 -- They get an unavailable
237 self:route_to_occupant(occupant, full_p);
239 -- use their own presences as templates
240 for full_jid, pr in occupant:each_session() do
242 pr.attr.to = full_jid;
243 -- You can always see your own full jids
244 pr:add_child(full_x);
245 self:route_stanza(pr);
250 function room_mt:send_occupant_list(to, filter)
251 local to_bare = jid_bare(to);
252 local is_anonymous = true;
253 local whois = self:get_whois();
254 if whois ~= "anyone" then
255 local affiliation = self:get_affiliation(to);
256 if affiliation ~= "admin" and affiliation ~= "owner" then
257 local occupant = self:get_occupant_by_real_jid(to);
258 if not occupant or can_see_real_jids(whois, occupant) then
259 is_anonymous = false;
263 for occupant_jid, occupant in self:each_occupant() do
264 if filter == nil or filter(occupant_jid, occupant) then
265 local x = st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
266 self:build_item_list(occupant, x, is_anonymous and to_bare ~= occupant.bare_jid); -- can always see your own jids
267 local pres = st.clone(occupant:get_presence());
270 self:route_stanza(pres);
275 function room_mt:get_disco_info(stanza)
276 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#info");
277 local form = dataform.new {
278 { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" };
280 module:fire_event("muc-disco#info", {room = self; reply = reply; form = form;});
281 reply:add_child(form:form(nil, "result"));
284 module:hook("muc-disco#info", function(event)
285 event.reply:tag("feature", {var = "http://jabber.org/protocol/muc"}):up();
287 module:hook("muc-disco#info", function(event)
288 local count = iterators.count(event.room:each_occupant());
289 table.insert(event.form, { name = "muc#roominfo_occupants", label = "Number of occupants", value = tostring(count) });
292 function room_mt:get_disco_items(stanza)
293 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
294 for room_jid in self:each_occupant() do
295 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
300 function room_mt:handle_kickable(origin, stanza)
301 local real_jid = stanza.attr.from;
302 local occupant = self:get_occupant_by_real_jid(real_jid);
303 if occupant == nil then return nil; end
304 local type, condition, text = stanza:get_error();
305 local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
307 error_message = error_message..": "..text;
309 occupant:set_session(real_jid, st.presence({type="unavailable"})
310 :tag('status'):text(error_message));
311 self:save_occupant(occupant);
312 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
313 :tag("status", {code = "307"})
314 self:publicise_occupant_status(occupant, x);
318 -- Give the room creator owner affiliation
319 module:hook("muc-room-pre-create", function(event)
320 event.room:set_affiliation(true, jid_bare(event.stanza.attr.from), "owner");
323 -- check if user is banned
324 module:hook("muc-occupant-pre-join", function(event)
325 local room, stanza = event.room, event.stanza;
326 local affiliation = room:get_affiliation(stanza.attr.from);
327 if affiliation == "outcast" then
328 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
329 reply.tags[1].attr.code = "403";
330 event.origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
335 function room_mt:handle_presence_to_occupant(origin, stanza)
336 local type = stanza.attr.type;
337 if type == "error" then -- error, kick em out!
338 return self:handle_kickable(origin, stanza)
339 elseif type == nil or type == "unavailable" then
340 local real_jid = stanza.attr.from;
341 local bare_jid = jid_bare(real_jid);
342 local orig_occupant, dest_occupant;
343 local is_new_room = next(self._affiliations) == nil;
345 if type == "unavailable" then return true; end -- Unavailable from someone not in the room
346 if module:fire_event("muc-room-pre-create", {
350 }) then return true; end
352 orig_occupant = self:get_occupant_by_real_jid(real_jid);
353 if type == "unavailable" and orig_occupant == nil then return true; end -- Unavailable from someone not in the room
355 local is_first_dest_session;
356 if type == "unavailable" then
357 -- dest_occupant = nil
358 elseif orig_occupant and orig_occupant.nick == stanza.attr.to then -- Just a presence update
359 log("debug", "presence update for %s from session %s", orig_occupant.nick, real_jid);
360 dest_occupant = orig_occupant;
362 local dest_jid = stanza.attr.to;
363 dest_occupant = self:get_occupant_by_nick(dest_jid);
364 if dest_occupant == nil then
365 log("debug", "no occupant found for %s; creating new occupant object for %s", dest_jid, real_jid);
366 is_first_dest_session = true;
367 dest_occupant = self:new_occupant(bare_jid, dest_jid);
369 is_first_dest_session = false;
372 local is_last_orig_session;
373 if orig_occupant ~= nil then
374 -- Is there are least 2 sessions?
375 local iter, ob, last = orig_occupant:each_session();
376 is_last_orig_session = iter(ob, iter(ob, last)) == nil;
379 local event, event_name = {
383 is_first_session = is_first_dest_session;
384 is_last_session = is_last_orig_session;
386 if orig_occupant == nil then
387 event_name = "muc-occupant-pre-join";
388 event.is_new_room = is_new_room;
389 elseif dest_occupant == nil then
390 event_name = "muc-occupant-pre-leave";
392 event_name = "muc-occupant-pre-change";
394 if module:fire_event(event_name, event) then return true; end
396 -- Check for nick conflicts
397 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
398 log("debug", "%s couldn't join due to nick conflict: %s", real_jid, dest_occupant.nick);
399 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
400 reply.tags[1].attr.code = "409";
401 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
405 -- Send presence stanza about original occupant
406 if orig_occupant ~= nil and orig_occupant ~= dest_occupant then
407 local orig_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
409 if dest_occupant == nil then -- Session is leaving
410 log("debug", "session %s is leaving occupant %s", real_jid, orig_occupant.nick);
411 if is_last_orig_session then
412 orig_occupant.role = nil;
414 orig_occupant:set_session(real_jid, stanza);
416 log("debug", "session %s is changing from occupant %s to %s", real_jid, orig_occupant.nick, dest_occupant.nick);
417 local generated_unavail = st.presence {from = orig_occupant.nick, to = real_jid, type = "unavailable"};
418 orig_occupant:set_session(real_jid, generated_unavail);
419 dest_nick = select(3, jid_split(dest_occupant.nick));
420 if not is_first_dest_session then -- User is swapping into another pre-existing session
421 log("debug", "session %s is swapping into multisession %s, showing it leave.", real_jid, dest_occupant.nick);
422 -- Show the other session leaving
423 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
424 :tag("status"):text("you are joining pre-existing session " .. dest_nick):up();
425 add_item(x, self:get_affiliation(bare_jid), "none");
426 local pr = st.presence{from = dest_occupant.nick, to = real_jid, type = "unavailable"}
428 self:route_stanza(pr);
430 if is_first_dest_session and is_last_orig_session then -- Normal nick change
431 log("debug", "no sessions in %s left; publically marking as nick change", orig_occupant.nick);
432 orig_x:tag("status", {code = "303";}):up();
433 else -- The session itself always needs to see a nick change
434 -- don't want to get our old nick's available presence,
435 -- so remove our session from there, and manually generate an unavailable
436 orig_occupant:remove_session(real_jid);
437 log("debug", "generating nick change for %s", real_jid);
438 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
439 -- self:build_item_list(orig_occupant, x, false, dest_nick); -- COMPAT: clients get confused if they see other items besides their own
440 add_item(x, self:get_affiliation(bare_jid), orig_occupant.role, real_jid, dest_nick);
441 x:tag("status", {code = "303";}):up();
442 x:tag("status", {code = "110";}):up();
443 self:route_stanza(generated_unavail:add_child(x));
444 dest_nick = nil; -- set dest_nick to nil; so general populance doesn't see it for whole orig_occupant
447 self:save_occupant(orig_occupant);
448 self:publicise_occupant_status(orig_occupant, orig_x, dest_nick);
450 if is_last_orig_session then
451 module:fire_event("muc-occupant-left", {room = self; nick = orig_occupant.nick;});
455 if dest_occupant ~= nil then
456 dest_occupant:set_session(real_jid, stanza);
457 local dest_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
459 dest_x:tag("status", {code = "201"}):up();
461 if orig_occupant == nil and self:get_whois() == "anyone" then
462 dest_x:tag("status", {code = "100"}):up();
464 self:save_occupant(dest_occupant);
466 if orig_occupant == nil then
467 -- Send occupant list to newly joined user
468 self:send_occupant_list(real_jid, function(nick, occupant)
469 -- Don't include self
470 return occupant:get_presence(real_jid) == nil;
473 self:publicise_occupant_status(dest_occupant, dest_x);
475 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
476 log("debug", "session %s split nicks; showing %s rejoining", real_jid, orig_occupant.nick);
477 -- Show the original nick joining again
478 local pr = st.clone(orig_occupant:get_presence());
479 pr.attr.to = real_jid;
480 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
481 self:build_item_list(orig_occupant, x, false);
482 -- TODO: new status code to inform client this was the multi-session it left?
484 self:route_stanza(pr);
487 if orig_occupant == nil and is_first_dest_session then
488 module:fire_event("muc-occupant-joined", {room = self; nick = dest_occupant.nick; stanza = stanza;});
491 elseif type ~= 'result' then -- bad type
492 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
493 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
499 function room_mt:handle_iq_to_occupant(origin, stanza)
500 local from, to = stanza.attr.from, stanza.attr.to;
501 local type = stanza.attr.type;
502 local id = stanza.attr.id;
503 local occupant = self:get_occupant_by_nick(to);
504 if (type == "error" or type == "result") then
505 do -- deconstruct_stanza_id
506 if not occupant then return nil; end
507 local from_jid, id, to_jid_hash = (base64.decode(stanza.attr.id) or ""):match("^(.+)%z(.*)%z(.+)$");
508 if not(from == from_jid or from == jid_bare(from_jid)) then return nil; end
509 local from_occupant_jid = self:get_occupant_jid(from_jid);
510 if from_occupant_jid == nil then return nil; end
512 for to_jid in occupant:each_session() do
513 if md5(to_jid) == to_jid_hash then
514 session_jid = to_jid;
518 if session_jid == nil then return nil; end
519 stanza.attr.from, stanza.attr.to, stanza.attr.id = from_jid, session_jid, id;
521 log("debug", "%s sent private iq stanza to %s (%s)", from, to, stanza.attr.to);
522 self:route_stanza(stanza);
523 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
525 else -- Type is "get" or "set"
526 local current_nick = self:get_occupant_jid(from);
527 if not current_nick then
528 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
531 if not occupant then -- recipient not in room
532 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
535 do -- construct_stanza_id
536 stanza.attr.id = base64.encode(occupant.jid.."\0"..stanza.attr.id.."\0"..md5(from));
538 stanza.attr.from, stanza.attr.to = current_nick, occupant.jid;
539 log("debug", "%s sent private iq stanza to %s (%s)", from, to, occupant.jid);
540 if stanza.tags[1].attr.xmlns == 'vcard-temp' then
541 stanza.attr.to = jid_bare(stanza.attr.to);
543 self:route_stanza(stanza);
544 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
549 function room_mt:handle_message_to_occupant(origin, stanza)
550 local from, to = stanza.attr.from, stanza.attr.to;
551 local current_nick = self:get_occupant_jid(from);
552 local type = stanza.attr.type;
553 if not current_nick then -- not in room
554 if type ~= "error" then
555 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
559 if type == "groupchat" then -- groupchat messages not allowed in PM
560 origin.send(st.error_reply(stanza, "modify", "bad-request"));
562 elseif type == "error" and is_kickable_error(stanza) then
563 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
564 return self:handle_kickable(origin, stanza); -- send unavailable
567 local o_data = self:get_occupant_by_nick(to);
569 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
572 log("debug", "%s sent private message stanza to %s (%s)", from, to, o_data.jid);
573 stanza:tag("x", { xmlns = "http://jabber.org/protocol/muc#user" }):up();
574 stanza.attr.from = current_nick;
575 self:route_to_occupant(o_data, stanza)
576 -- TODO: Remove x tag?
577 stanza.attr.from = from;
581 function room_mt:send_form(origin, stanza)
582 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
583 :add_child(self:get_form_layout(stanza.attr.from):form())
587 function room_mt:get_form_layout(actor)
588 local form = dataform.new({
589 title = "Configuration for "..self.jid,
590 instructions = "Complete and submit this form to configure the room.",
594 value = 'http://jabber.org/protocol/muc#roomconfig'
597 return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
600 function room_mt:process_form(origin, stanza)
601 local form = stanza.tags[1]:get_child("x", "jabber:x:data");
602 if form.attr.type == "cancel" then
603 origin.send(st.reply(stanza));
604 elseif form.attr.type == "submit" then
605 local fields = self:get_form_layout(stanza.attr.from):data(form);
606 if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then
607 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration"));
611 local event = {room = self; origin = origin; stanza = stanza; fields = fields; status_codes = {};};
612 function event.update_option(name, field, allowed)
613 local new = fields[field];
614 if new == nil then return; end
615 if allowed and not allowed[new] then return; end
616 if new == self["get_"..name](self) then return; end
617 event.status_codes["104"] = true;
618 self["set_"..name](self, new);
621 module:fire_event("muc-config-submitted", event);
623 if self.save then self:save(true); end
624 origin.send(st.reply(stanza));
626 if next(event.status_codes) then
627 local msg = st.message({type='groupchat', from=self.jid})
628 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
629 for code in pairs(event.status_codes) do
630 msg:tag("status", {code = code;}):up();
633 self:broadcast_message(msg);
636 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form"));
641 -- Removes everyone from the room
642 function room_mt:clear(x)
643 x = x or st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
644 local occupants_updated = {};
645 for nick, occupant in self:each_occupant() do
647 self:save_occupant(occupant);
648 occupants_updated[occupant] = true;
650 for occupant in pairs(occupants_updated) do
651 self:publicise_occupant_status(occupant, x);
652 module:fire_event("muc-occupant-left", { room = self; nick = occupant.nick; });
656 function room_mt:destroy(newjid, reason, password)
657 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
658 :tag("item", { affiliation='none', role='none' }):up()
659 :tag("destroy", {jid=newjid});
660 if reason then x:tag("reason"):text(reason):up(); end
661 if password then x:tag("password"):text(password):up(); end
664 module:fire_event("muc-room-destroyed", { room = self });
667 function room_mt:handle_disco_info_get_query(origin, stanza)
668 origin.send(self:get_disco_info(stanza));
672 function room_mt:handle_disco_items_get_query(origin, stanza)
673 origin.send(self:get_disco_items(stanza));
677 function room_mt:handle_admin_query_set_command(origin, stanza)
678 local item = stanza.tags[1].tags[1];
679 if item.attr.jid then -- Validate provided JID
680 item.attr.jid = jid_prep(item.attr.jid);
681 if not item.attr.jid then
682 origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
686 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
687 local occupant = self:get_occupant_by_nick(self.jid.."/"..item.attr.nick);
688 if occupant then item.attr.jid = occupant.jid; end
689 elseif not item.attr.nick and item.attr.jid then
690 local nick = self:get_occupant_jid(item.attr.jid);
691 if nick then item.attr.nick = select(3, jid_split(nick)); end
693 local actor = stanza.attr.from;
694 local reason = item:get_child_text("reason");
695 local success, errtype, err
696 if item.attr.affiliation and item.attr.jid and not item.attr.role then
697 success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, reason);
698 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
699 success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, reason);
701 success, errtype, err = nil, "cancel", "bad-request";
703 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
704 origin.send(st.reply(stanza));
708 function room_mt:handle_admin_query_get_command(origin, stanza)
709 local actor = stanza.attr.from;
710 local affiliation = self:get_affiliation(actor);
711 local item = stanza.tags[1].tags[1];
712 local _aff = item.attr.affiliation;
713 local _rol = item.attr.role;
714 if _aff and not _rol then
715 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
716 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
717 for jid, affiliation in pairs(self._affiliations) do
718 if affiliation == _aff then
719 reply:tag("item", {affiliation = _aff, jid = jid}):up();
725 origin.send(st.error_reply(stanza, "auth", "forbidden"));
728 elseif _rol and not _aff then
729 local role = self:get_role(self:get_occupant_jid(actor)) or self:get_default_role(affiliation);
730 if valid_roles[role or "none"] >= valid_roles.moderator then
731 if _rol == "none" then _rol = nil; end
732 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
733 -- TODO: whois check here? (though fully anonymous rooms are not supported)
734 for occupant_jid, occupant in self:each_occupant() do
735 if occupant.role == _rol then
736 local nick = select(3,jid_split(occupant_jid));
737 self:build_item_list(occupant, reply, false, nick);
740 origin.send(reply:up());
743 origin.send(st.error_reply(stanza, "auth", "forbidden"));
747 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
752 function room_mt:handle_owner_query_get_to_room(origin, stanza)
753 if self:get_affiliation(stanza.attr.from) ~= "owner" then
754 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
758 self:send_form(origin, stanza);
761 function room_mt:handle_owner_query_set_to_room(origin, stanza)
762 if self:get_affiliation(stanza.attr.from) ~= "owner" then
763 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
767 local child = stanza.tags[1].tags[1];
769 origin.send(st.error_reply(stanza, "modify", "bad-request"));
771 elseif child.name == "destroy" then
772 local newjid = child.attr.jid;
773 local reason = child:get_child_text("reason");
774 local password = child:get_child_text("password");
775 self:destroy(newjid, reason, password);
776 origin.send(st.reply(stanza));
778 elseif child.name == "x" and child.attr.xmlns == "jabber:x:data" then
779 return self:process_form(origin, stanza);
781 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
786 function room_mt:handle_groupchat_to_room(origin, stanza)
787 -- Prosody has made the decision that messages with <subject/> are exclusively subject changes
788 -- e.g. body will be ignored; even if the subject change was not allowed
789 if stanza:get_child("subject") then
790 return module:fire_event("muc-subject-change", {room = self, origin = origin, stanza = stanza});
792 local from = stanza.attr.from;
793 local occupant = self:get_occupant_by_real_jid(from);
794 if not occupant then -- not in room
795 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
797 elseif occupant.role == "visitor" then
798 origin.send(st.error_reply(stanza, "auth", "forbidden"));
801 stanza.attr.from = occupant.nick;
802 self:broadcast_message(stanza);
803 stanza.attr.from = from;
807 -- hack - some buggy clients send presence updates to the room rather than their nick
808 function room_mt:handle_presence_to_room(origin, stanza)
809 local current_nick = self:get_occupant_jid(stanza.attr.from);
812 local to = stanza.attr.to;
813 stanza.attr.to = current_nick;
814 handled = self:handle_presence_to_occupant(origin, stanza);
820 -- Need visitor role or higher to invite
821 module:hook("muc-pre-invite", function(event)
822 local room, stanza = event.room, event.stanza;
823 local _from, _to = stanza.attr.from, stanza.attr.to;
824 local inviter = room:get_occupant_by_real_jid(_from);
825 local role = inviter and inviter.role or room:get_default_role(room:get_affiliation(_from));
826 if valid_roles[role or "none"] <= valid_roles.visitor then
827 event.origin.send(st.error_reply(stanza, "auth", "forbidden"));
832 function room_mt:handle_mediated_invite(origin, stanza)
833 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
834 local invitee = jid_prep(payload.attr.to);
836 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
838 elseif module:fire_event("muc-pre-invite", {room = self, origin = origin, stanza = stanza}) then
841 local invite = st.message({from = self.jid, to = invitee, id = stanza.attr.id})
842 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
843 :tag('invite', {from = stanza.attr.from;})
844 :tag('reason'):text(payload:get_child_text("reason")):up()
847 if not module:fire_event("muc-invite", {room = self, stanza = invite, origin = origin, incoming = stanza}) then
848 self:route_stanza(invite);
853 -- COMPAT: Some older clients expect this
854 module:hook("muc-invite", function(event)
855 local room, stanza = event.room, event.stanza;
856 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
857 local reason = invite:get_child_text("reason");
858 stanza:tag('x', {xmlns = "jabber:x:conference"; jid = room.jid;})
863 -- Add a plain message for clients which don't support invites
864 module:hook("muc-invite", function(event)
865 local room, stanza = event.room, event.stanza;
866 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
867 local reason = invite:get_child_text("reason") or "";
869 :text(invite.attr.from.." invited you to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
873 function room_mt:handle_mediated_decline(origin, stanza)
874 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
875 local declinee = jid_prep(payload.attr.to);
877 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
879 elseif module:fire_event("muc-pre-decline", {room = self, origin = origin, stanza = stanza}) then
882 local decline = st.message({from = self.jid, to = declinee, id = stanza.attr.id})
883 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
884 :tag("decline", {from = stanza.attr.from})
885 :tag("reason"):text(payload:get_child_text("reason")):up()
888 if not module:fire_event("muc-decline", {room = self, stanza = decline, origin = origin, incoming = stanza}) then
889 local occupant = self:get_occupant_by_real_jid(decline.attr.to);
891 self:route_to_occupant(occupant, decline);
893 self:route_stanza(decline);
899 -- Add a plain message for clients which don't support declines
900 module:hook("muc-decline", function(event)
901 local room, stanza = event.room, event.stanza;
902 local decline = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
903 local reason = decline:get_child_text("reason") or "";
905 :text(decline.attr.from.." declined your invite to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
909 function room_mt:handle_message_to_room(origin, stanza)
910 local type = stanza.attr.type;
911 if type == "groupchat" then
912 return self:handle_groupchat_to_room(origin, stanza)
913 elseif type == "error" and is_kickable_error(stanza) then
914 return self:handle_kickable(origin, stanza)
915 elseif type == nil then
916 local x = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
918 local payload = x.tags[1];
919 if payload == nil then
921 elseif payload.name == "invite" and payload.attr.to then
922 return self:handle_mediated_invite(origin, stanza)
923 elseif payload.name == "decline" and payload.attr.to then
924 return self:handle_mediated_decline(origin, stanza)
926 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
932 function room_mt:route_stanza(stanza)
936 function room_mt:get_affiliation(jid)
937 local node, host, resource = jid_split(jid);
938 local bare = node and node.."@"..host or host;
939 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
940 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
944 function room_mt:set_affiliation(actor, jid, affiliation, reason)
945 if not actor then return nil, "modify", "not-acceptable"; end;
949 if valid_affiliations[affiliation or "none"] == nil then
950 return nil, "modify", "not-acceptable";
952 affiliation = affiliation ~= "none" and affiliation or nil; -- coerces `affiliation == false` to `nil`
954 local target_affiliation = self._affiliations[jid]; -- Raw; don't want to check against host
955 local is_downgrade = valid_affiliations[target_affiliation or "none"] > valid_affiliations[affiliation or "none"];
957 if actor ~= true then
958 local actor_bare = jid_bare(actor);
959 local actor_affiliation = self._affiliations[actor_bare];
960 if actor_affiliation == "owner" then
961 if actor_bare == jid then -- self change
962 -- need at least one owner
963 local is_last = true;
964 for j, aff in pairs(self._affiliations) do if j ~= jid and aff == "owner" then is_last = false; break; end end
966 return nil, "cancel", "conflict";
969 -- owners can do anything else
970 elseif affiliation == "owner" or affiliation == "admin"
971 or actor_affiliation ~= "admin"
972 or target_affiliation == "owner" or target_affiliation == "admin" then
973 -- Can't demote owners or other admins
974 return nil, "cancel", "not-allowed";
979 self._affiliations[jid] = affiliation;
982 local role = self:get_default_role(affiliation);
983 local role_rank = valid_roles[role or "none"];
984 local occupants_updated = {}; -- Filled with old roles
985 for nick, occupant in self:each_occupant() do
986 if occupant.bare_jid == jid then
987 -- need to publcize in all cases; as affiliation in <item/> has changed.
988 occupants_updated[occupant] = occupant.role;
989 if occupant.role ~= role and (
991 valid_roles[occupant.role or "none"] < role_rank -- upgrade
993 occupant.role = role;
994 self:save_occupant(occupant);
999 -- Tell the room of the new occupant affiliations+roles
1000 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1001 if not role then -- getting kicked
1002 if affiliation == "outcast" then
1003 x:tag("status", {code="301"}):up(); -- banned
1005 x:tag("status", {code="321"}):up(); -- affiliation change
1008 local is_semi_anonymous = self:get_whois() == "moderators";
1009 for occupant, old_role in pairs(occupants_updated) do
1010 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1011 if is_semi_anonymous and
1012 (old_role == "moderator" and occupant.role ~= "moderator") or
1013 (old_role ~= "moderator" and occupant.role == "moderator") then -- Has gained or lost moderator status
1014 -- Send everyone else's presences (as jid visibility has changed)
1015 for real_jid in occupant:each_session() do
1016 self:send_occupant_list(real_jid, function(occupant_jid, occupant)
1017 return occupant.bare_jid ~= jid;
1023 if self.save then self:save(); end
1027 function room_mt:get_role(nick)
1028 local occupant = self:get_occupant_by_nick(nick);
1029 return occupant and occupant.role or nil;
1032 function room_mt:set_role(actor, occupant_jid, role, reason)
1033 if not actor then return nil, "modify", "not-acceptable"; end
1035 local occupant = self:get_occupant_by_nick(occupant_jid);
1036 if not occupant then return nil, "modify", "not-acceptable"; end
1038 if valid_roles[role or "none"] == nil then
1039 return nil, "modify", "not-acceptable";
1041 role = role ~= "none" and role or nil; -- coerces `role == false` to `nil`
1043 if actor ~= true then
1044 -- Can't do anything to other owners or admins
1045 local occupant_affiliation = self:get_affiliation(occupant.bare_jid);
1046 if occupant_affiliation == "owner" and occupant_affiliation == "admin" then
1047 return nil, "cancel", "not-allowed";
1050 -- If you are trying to give or take moderator role you need to be an owner or admin
1051 if occupant.role == "moderator" or role == "moderator" then
1052 local actor_affiliation = self:get_affiliation(actor);
1053 if actor_affiliation ~= "owner" and actor_affiliation ~= "admin" then
1054 return nil, "cancel", "not-allowed";
1058 -- Need to be in the room and a moderator
1059 local actor_occupant = self:get_occupant_by_real_jid(actor);
1060 if not actor_occupant or actor_occupant.role ~= "moderator" then
1061 return nil, "cancel", "not-allowed";
1065 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1067 x:tag("status", {code = "307"}):up();
1069 occupant.role = role;
1070 self:save_occupant(occupant);
1071 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1075 local name = module:require "muc/name";
1076 room_mt.get_name = name.get;
1077 room_mt.set_name = name.set;
1079 local description = module:require "muc/description";
1080 room_mt.get_description = description.get;
1081 room_mt.set_description = description.set;
1083 local hidden = module:require "muc/hidden";
1084 room_mt.get_hidden = hidden.get;
1085 room_mt.set_hidden = hidden.set;
1086 function room_mt:get_public()
1087 return not self:get_hidden();
1089 function room_mt:set_public(public)
1090 return self:set_hidden(not public);
1093 local password = module:require "muc/password";
1094 room_mt.get_password = password.get;
1095 room_mt.set_password = password.set;
1097 local whois = module:require "muc/whois";
1098 room_mt.get_whois = whois.get;
1099 room_mt.set_whois = whois.set;
1101 local members_only = module:require "muc/members_only";
1102 room_mt.get_members_only = members_only.get;
1103 room_mt.set_members_only = members_only.set;
1105 local moderated = module:require "muc/moderated";
1106 room_mt.get_moderated = moderated.get;
1107 room_mt.set_moderated = moderated.set;
1109 local persistent = module:require "muc/persistent";
1110 room_mt.get_persistent = persistent.get;
1111 room_mt.set_persistent = persistent.set;
1113 local subject = module:require "muc/subject";
1114 room_mt.get_changesubject = subject.get_changesubject;
1115 room_mt.set_changesubject = subject.set_changesubject;
1116 room_mt.get_subject = subject.get;
1117 room_mt.set_subject = subject.set;
1118 room_mt.send_subject = subject.send;
1120 local history = module:require "muc/history";
1121 room_mt.send_history = history.send;
1122 room_mt.get_historylength = history.get_length;
1123 room_mt.set_historylength = history.set_length;
1125 local _M = {}; -- module "muc"
1127 function _M.new_room(jid, config)
1128 return setmetatable({
1138 _M.room_mt = room_mt;