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;
103 if occupant.role ~= nil and next(occupant.sessions) then
104 for real_jid, presence in occupant:each_session() do
105 self._jid_nick[real_jid] = occupant.nick;
110 self._occupants[id] = occupant
113 function room_mt:route_to_occupant(occupant, stanza)
114 local to = stanza.attr.to;
115 for jid, pr in occupant:each_session() do
116 if pr.attr.type ~= "unavailable" then
117 stanza.attr.to = jid;
118 self:route_stanza(stanza);
124 -- actor is the attribute table
125 local function add_item(x, affiliation, role, jid, nick, actor, reason)
126 x:tag("item", {affiliation = affiliation; role = role; jid = jid; nick = nick;})
128 x:tag("actor", actor):up()
131 x:tag("reason"):text(reason):up()
137 -- actor is (real) jid
138 function room_mt:build_item_list(occupant, x, is_anonymous, nick, actor, reason)
139 local affiliation = self:get_affiliation(occupant.bare_jid) or "none";
140 local role = occupant.role or "none";
143 actor_attr = {nick = select(3,jid_split(self:get_occupant_jid(actor)))};
146 add_item(x, affiliation, role, nil, nick, actor_attr, reason);
149 actor_attr.jid = actor;
151 for real_jid, session in occupant:each_session() do
152 add_item(x, affiliation, role, real_jid, nick, actor_attr, reason);
158 function room_mt:broadcast_message(stanza)
159 module:fire_event("muc-broadcast-message", {room = self, stanza = stanza});
160 self:broadcast(stanza);
163 -- Broadcast a stanza to all occupants in the room.
164 -- optionally checks conditional called with (nick, occupant)
165 function room_mt:broadcast(stanza, cond_func)
166 for nick, occupant in self:each_occupant() do
167 if cond_func == nil or cond_func(nick, occupant) then
168 self:route_to_occupant(occupant, stanza)
173 local function can_see_real_jids(whois, occupant)
174 if whois == "anyone" then
176 elseif whois == "moderators" then
177 return valid_roles[occupant.role or "none"] >= valid_roles.moderator;
181 local function get_base_presence(occupant)
182 if occupant.role ~= nil then
183 -- Try to use main jid's presence
184 local pr = occupant:get_presence();
189 return st.presence {from = occupant.nick; type = "unavailable";};
192 -- Broadcasts an occupant's presence to the whole room
193 -- Takes the x element that goes into the stanzas
194 function room_mt:publicise_occupant_status(occupant, base_x, nick, actor, reason)
195 -- Build real jid and (optionally) occupant jid template presences
196 local function get_presence(is_anonymous)
197 local x = st.clone(base_x);
198 self:build_item_list(occupant, x, is_anonymous, nick, actor, reason);
199 return get_base_presence(occupant):add_child(x), x;
201 local full_p, full_x = get_presence(false);
202 local anon_p, anon_x;
203 local function get_anon_p()
204 if anon_p == nil then
205 anon_p, anon_x = get_presence(true);
207 return anon_p, anon_x;
210 local whois = self:get_whois();
213 for nick, n_occupant in self:each_occupant() do
214 if nick ~= occupant.nick then
216 if can_see_real_jids(whois, occupant) or occupant.bare_jid == n_occupant.bare_jid then
221 self:route_to_occupant(n_occupant, pr);
225 -- Presences for occupant itself
226 full_x:tag("status", {code = "110";}):up();
227 if occupant.role == nil then
228 -- They get an unavailable
229 self:route_to_occupant(occupant, full_p);
231 -- use their own presences as templates
232 for full_jid, pr in occupant:each_session() do
234 pr.attr.to = full_jid;
235 -- You can always see your own full jids
236 pr:add_child(full_x);
237 self:route_stanza(pr);
242 function room_mt:send_occupant_list(to, filter)
243 local to_bare = jid_bare(to);
244 local is_anonymous = true;
245 local whois = self:get_whois();
246 if whois ~= "anyone" then
247 local affiliation = self:get_affiliation(to);
248 if affiliation ~= "admin" and affiliation ~= "owner" then
249 local occupant = self:get_occupant_by_real_jid(to);
250 if not occupant or can_see_real_jids(whois, occupant) then
251 is_anonymous = false;
255 for occupant_jid, occupant in self:each_occupant() do
256 if filter == nil or filter(occupant_jid, occupant) then
257 local x = st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
258 self:build_item_list(occupant, x, is_anonymous and to_bare ~= occupant.bare_jid); -- can always see your own jids
259 local pres = st.clone(occupant:get_presence());
262 self:route_stanza(pres);
267 function room_mt:get_disco_info(stanza)
268 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#info");
269 local form = dataform.new {
270 { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" };
272 module:fire_event("muc-disco#info", {room = self; reply = reply; form = form;});
273 reply:add_child(form:form(nil, "result"));
276 module:hook("muc-disco#info", function(event)
277 event.reply:tag("feature", {var = "http://jabber.org/protocol/muc"}):up();
279 module:hook("muc-disco#info", function(event)
280 local count = iterators.count(event.room:each_occupant());
281 table.insert(event.form, { name = "muc#roominfo_occupants", label = "Number of occupants", value = tostring(count) });
284 function room_mt:get_disco_items(stanza)
285 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
286 for room_jid in self:each_occupant() do
287 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
292 function room_mt:handle_kickable(origin, stanza)
293 local real_jid = stanza.attr.from;
294 local occupant = self:get_occupant_by_real_jid(real_jid);
295 if occupant == nil then return nil; end
296 local type, condition, text = stanza:get_error();
297 local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
299 error_message = error_message..": "..text;
301 occupant:set_session(real_jid, st.presence({type="unavailable"})
302 :tag('status'):text(error_message));
303 self:save_occupant(occupant);
304 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
305 :tag("status", {code = "307"})
306 self:publicise_occupant_status(occupant, x);
310 -- Give the room creator owner affiliation
311 module:hook("muc-room-pre-create", function(event)
312 event.room:set_affiliation(true, jid_bare(event.stanza.attr.from), "owner");
315 -- check if user is banned
316 module:hook("muc-occupant-pre-join", function(event)
317 local room, stanza = event.room, event.stanza;
318 local affiliation = room:get_affiliation(stanza.attr.from);
319 if affiliation == "outcast" then
320 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
321 reply.tags[1].attr.code = "403";
322 event.origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
327 function room_mt:handle_presence_to_occupant(origin, stanza)
328 local type = stanza.attr.type;
329 if type == "error" then -- error, kick em out!
330 return self:handle_kickable(origin, stanza)
331 elseif type == nil or type == "unavailable" then
332 local real_jid = stanza.attr.from;
333 local bare_jid = jid_bare(real_jid);
334 local orig_occupant, dest_occupant;
335 local is_new_room = next(self._affiliations) == nil;
337 if type == "unavailable" then return true; end -- Unavailable from someone not in the room
338 if module:fire_event("muc-room-pre-create", {
342 }) then return true; end
344 orig_occupant = self:get_occupant_by_real_jid(real_jid);
345 if type == "unavailable" and orig_occupant == nil then return true; end -- Unavailable from someone not in the room
347 local is_first_dest_session;
348 if type == "unavailable" then
349 -- dest_occupant = nil
350 elseif orig_occupant and orig_occupant.nick == stanza.attr.to then -- Just a presence update
351 log("debug", "presence update for %s from session %s", orig_occupant.nick, real_jid);
352 dest_occupant = orig_occupant;
354 local dest_jid = stanza.attr.to;
355 dest_occupant = self:get_occupant_by_nick(dest_jid);
356 if dest_occupant == nil then
357 log("debug", "no occupant found for %s; creating new occupant object for %s", dest_jid, real_jid);
358 is_first_dest_session = true;
359 dest_occupant = self:new_occupant(bare_jid, dest_jid);
361 is_first_dest_session = false;
364 local is_last_orig_session;
365 if orig_occupant ~= nil then
366 -- Is there are least 2 sessions?
367 local iter, ob, last = orig_occupant:each_session();
368 is_last_orig_session = iter(ob, iter(ob, last)) == nil;
371 local event, event_name = {
375 is_first_session = is_first_dest_session;
376 is_last_session = is_last_orig_session;
378 if orig_occupant == nil then
379 event_name = "muc-occupant-pre-join";
380 event.is_new_room = is_new_room;
381 elseif dest_occupant == nil then
382 event_name = "muc-occupant-pre-leave";
384 event_name = "muc-occupant-pre-change";
386 if module:fire_event(event_name, event) then return true; end
388 -- Check for nick conflicts
389 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
390 log("debug", "%s couldn't join due to nick conflict: %s", real_jid, dest_occupant.nick);
391 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
392 reply.tags[1].attr.code = "409";
393 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
397 -- Send presence stanza about original occupant
398 if orig_occupant ~= nil and orig_occupant ~= dest_occupant then
399 local orig_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
401 if dest_occupant == nil then -- Session is leaving
402 log("debug", "session %s is leaving occupant %s", real_jid, orig_occupant.nick);
403 orig_occupant.role = nil;
404 orig_occupant:set_session(real_jid, stanza);
406 log("debug", "session %s is changing from occupant %s to %s", real_jid, orig_occupant.nick, dest_occupant.nick);
407 local generated_unavail = st.presence {from = orig_occupant.nick, to = real_jid, type = "unavailable"};
408 orig_occupant:set_session(real_jid, generated_unavail);
409 dest_nick = select(3, jid_split(dest_occupant.nick));
410 if not is_first_dest_session then -- User is swapping into another pre-existing session
411 log("debug", "session %s is swapping into multisession %s, showing it leave.", real_jid, dest_occupant.nick);
412 -- Show the other session leaving
413 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
414 :tag("status"):text("you are joining pre-existing session " .. dest_nick):up();
415 add_item(x, self:get_affiliation(bare_jid), "none");
416 local pr = st.presence{from = dest_occupant.nick, to = real_jid, type = "unavailable"}
418 self:route_stanza(pr);
420 if is_first_dest_session and is_last_orig_session then -- Normal nick change
421 log("debug", "no sessions in %s left; publically marking as nick change", orig_occupant.nick);
422 orig_x:tag("status", {code = "303";}):up();
423 else -- The session itself always needs to see a nick change
424 -- don't want to get our old nick's available presence,
425 -- so remove our session from there, and manually generate an unavailable
426 orig_occupant:remove_session(real_jid);
427 log("debug", "generating nick change for %s", real_jid);
428 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
429 -- self:build_item_list(orig_occupant, x, false, dest_nick); -- COMPAT: clients get confused if they see other items besides their own
430 add_item(x, self:get_affiliation(bare_jid), orig_occupant.role, real_jid, dest_nick);
431 x:tag("status", {code = "303";}):up();
432 x:tag("status", {code = "110";}):up();
433 self:route_stanza(generated_unavail:add_child(x));
434 dest_nick = nil; -- set dest_nick to nil; so general populance doesn't see it for whole orig_occupant
437 self:save_occupant(orig_occupant);
438 self:publicise_occupant_status(orig_occupant, orig_x, dest_nick);
440 if is_last_orig_session then
441 module:fire_event("muc-occupant-left", {room = self; nick = orig_occupant.nick;});
445 if dest_occupant ~= nil then
446 dest_occupant:set_session(real_jid, stanza);
447 local dest_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
449 dest_x:tag("status", {code = "201"}):up();
451 if orig_occupant == nil and self:get_whois() == "anyone" then
452 dest_x:tag("status", {code = "100"}):up();
454 self:save_occupant(dest_occupant);
456 if orig_occupant == nil and is_first_dest_session then
457 -- Send occupant list to newly joined user
458 self:send_occupant_list(real_jid, function(nick, occupant)
459 -- Don't include self
460 return occupant:get_presence(real_jid) == nil;
463 self:publicise_occupant_status(dest_occupant, dest_x);
465 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
466 log("debug", "session %s split nicks; showing %s rejoining", real_jid, orig_occupant.nick);
467 -- Show the original nick joining again
468 local pr = st.clone(orig_occupant:get_presence());
469 pr.attr.to = real_jid;
470 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
471 self:build_item_list(orig_occupant, x, false);
472 -- TODO: new status code to inform client this was the multi-session it left?
474 self:route_stanza(pr);
477 if orig_occupant == nil and is_first_dest_session then
478 module:fire_event("muc-occupant-joined", {room = self; nick = dest_occupant.nick; stanza = stanza;});
481 elseif type ~= 'result' then -- bad type
482 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
483 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
489 function room_mt:handle_iq_to_occupant(origin, stanza)
490 local from, to = stanza.attr.from, stanza.attr.to;
491 local type = stanza.attr.type;
492 local id = stanza.attr.id;
493 local occupant = self:get_occupant_by_nick(to);
494 if (type == "error" or type == "result") then
495 do -- deconstruct_stanza_id
496 if not occupant then return nil; end
497 local from_jid, id, to_jid_hash = (base64.decode(stanza.attr.id) or ""):match("^(.+)%z(.*)%z(.+)$");
498 if not(from == from_jid or from == jid_bare(from_jid)) then return nil; end
499 local from_occupant_jid = self:get_occupant_jid(from_jid);
500 if from_occupant_jid == nil then return nil; end
502 for to_jid in occupant:each_session() do
503 if md5(to_jid) == to_jid_hash then
504 session_jid = to_jid;
508 if session_jid == nil then return nil; end
509 stanza.attr.from, stanza.attr.to, stanza.attr.id = from_jid, session_jid, id;
511 log("debug", "%s sent private iq stanza to %s (%s)", from, to, stanza.attr.to);
512 self:route_stanza(stanza);
513 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
515 else -- Type is "get" or "set"
516 local current_nick = self:get_occupant_jid(from);
517 if not current_nick then
518 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
521 if not occupant then -- recipient not in room
522 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
525 do -- construct_stanza_id
526 stanza.attr.id = base64.encode(occupant.jid.."\0"..stanza.attr.id.."\0"..md5(from));
528 stanza.attr.from, stanza.attr.to = current_nick, occupant.jid;
529 log("debug", "%s sent private iq stanza to %s (%s)", from, to, occupant.jid);
530 if stanza.tags[1].attr.xmlns == 'vcard-temp' then
531 stanza.attr.to = jid_bare(stanza.attr.to);
533 self:route_stanza(stanza);
534 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
539 function room_mt:handle_message_to_occupant(origin, stanza)
540 local from, to = stanza.attr.from, stanza.attr.to;
541 local current_nick = self:get_occupant_jid(from);
542 local type = stanza.attr.type;
543 if not current_nick then -- not in room
544 if type ~= "error" then
545 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
549 if type == "groupchat" then -- groupchat messages not allowed in PM
550 origin.send(st.error_reply(stanza, "modify", "bad-request"));
552 elseif type == "error" and is_kickable_error(stanza) then
553 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
554 return self:handle_kickable(origin, stanza); -- send unavailable
557 local o_data = self:get_occupant_by_nick(to);
559 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
562 log("debug", "%s sent private message stanza to %s (%s)", from, to, o_data.jid);
563 stanza:tag("x", { xmlns = "http://jabber.org/protocol/muc#user" }):up();
564 stanza.attr.from = current_nick;
565 self:route_to_occupant(o_data, stanza)
566 -- TODO: Remove x tag?
567 stanza.attr.from = from;
571 function room_mt:send_form(origin, stanza)
572 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
573 :add_child(self:get_form_layout(stanza.attr.from):form())
577 function room_mt:get_form_layout(actor)
578 local form = dataform.new({
579 title = "Configuration for "..self.jid,
580 instructions = "Complete and submit this form to configure the room.",
584 value = 'http://jabber.org/protocol/muc#roomconfig'
587 return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
590 function room_mt:process_form(origin, stanza)
591 local form = stanza.tags[1]:get_child("x", "jabber:x:data");
592 if form.attr.type == "cancel" then
593 origin.send(st.reply(stanza));
594 elseif form.attr.type == "submit" then
595 local fields = self:get_form_layout(stanza.attr.from):data(form);
596 if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then
597 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration"));
601 local event = {room = self; origin = origin; stanza = stanza; fields = fields; status_codes = {};};
602 function event.update_option(name, field, allowed)
603 local new = fields[field];
604 if new == nil then return; end
605 if allowed and not allowed[new] then return; end
606 if new == self["get_"..name](self) then return; end
607 event.status_codes["104"] = true;
608 self["set_"..name](self, new);
611 module:fire_event("muc-config-submitted", event);
613 if self.save then self:save(true); end
614 origin.send(st.reply(stanza));
616 if next(event.status_codes) then
617 local msg = st.message({type='groupchat', from=self.jid})
618 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
619 for code in pairs(event.status_codes) do
620 msg:tag("status", {code = code;}):up();
623 self:broadcast_message(msg);
626 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form"));
631 -- Removes everyone from the room
632 function room_mt:clear(x)
633 x = x or st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
634 local occupants_updated = {};
635 for nick, occupant in self:each_occupant() do
637 self:save_occupant(occupant);
638 occupants_updated[occupant] = true;
640 for occupant in pairs(occupants_updated) do
641 self:publicise_occupant_status(occupant, x);
642 module:fire_event("muc-occupant-left", { room = self; nick = occupant.nick; });
646 function room_mt:destroy(newjid, reason, password)
647 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
648 :tag("item", { affiliation='none', role='none' }):up()
649 :tag("destroy", {jid=newjid});
650 if reason then x:tag("reason"):text(reason):up(); end
651 if password then x:tag("password"):text(password):up(); end
654 module:fire_event("muc-room-destroyed", { room = self });
657 function room_mt:handle_disco_info_get_query(origin, stanza)
658 origin.send(self:get_disco_info(stanza));
662 function room_mt:handle_disco_items_get_query(origin, stanza)
663 origin.send(self:get_disco_items(stanza));
667 function room_mt:handle_admin_query_set_command(origin, stanza)
668 local item = stanza.tags[1].tags[1];
669 if item.attr.jid then -- Validate provided JID
670 item.attr.jid = jid_prep(item.attr.jid);
671 if not item.attr.jid then
672 origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
676 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
677 local occupant = self:get_occupant_by_nick(self.jid.."/"..item.attr.nick);
678 if occupant then item.attr.jid = occupant.jid; end
679 elseif not item.attr.nick and item.attr.jid then
680 local nick = self:get_occupant_jid(item.attr.jid);
681 if nick then item.attr.nick = select(3, jid_split(nick)); end
683 local actor = stanza.attr.from;
684 local reason = item:get_child_text("reason");
685 local success, errtype, err
686 if item.attr.affiliation and item.attr.jid and not item.attr.role then
687 success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, reason);
688 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
689 success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, reason);
691 success, errtype, err = nil, "cancel", "bad-request";
693 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
694 origin.send(st.reply(stanza));
698 function room_mt:handle_admin_query_get_command(origin, stanza)
699 local actor = stanza.attr.from;
700 local affiliation = self:get_affiliation(actor);
701 local item = stanza.tags[1].tags[1];
702 local _aff = item.attr.affiliation;
703 local _rol = item.attr.role;
704 if _aff and not _rol then
705 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
706 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
707 for jid, affiliation in pairs(self._affiliations) do
708 if affiliation == _aff then
709 reply:tag("item", {affiliation = _aff, jid = jid}):up();
715 origin.send(st.error_reply(stanza, "auth", "forbidden"));
718 elseif _rol and not _aff then
719 local role = self:get_role(self:get_occupant_jid(actor)) or self:get_default_role(affiliation);
720 if valid_roles[role or "none"] >= valid_roles.moderator then
721 if _rol == "none" then _rol = nil; end
722 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
723 -- TODO: whois check here? (though fully anonymous rooms are not supported)
724 for occupant_jid, occupant in self:each_occupant() do
725 if occupant.role == _rol then
726 local nick = select(3,jid_split(occupant_jid));
727 self:build_item_list(occupant, reply, false, nick);
730 origin.send(reply:up());
733 origin.send(st.error_reply(stanza, "auth", "forbidden"));
737 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
742 function room_mt:handle_owner_query_get_to_room(origin, stanza)
743 if self:get_affiliation(stanza.attr.from) ~= "owner" then
744 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
748 self:send_form(origin, stanza);
751 function room_mt:handle_owner_query_set_to_room(origin, stanza)
752 if self:get_affiliation(stanza.attr.from) ~= "owner" then
753 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
757 local child = stanza.tags[1].tags[1];
759 origin.send(st.error_reply(stanza, "modify", "bad-request"));
761 elseif child.name == "destroy" then
762 local newjid = child.attr.jid;
763 local reason = child:get_child_text("reason");
764 local password = child:get_child_text("password");
765 self:destroy(newjid, reason, password);
766 origin.send(st.reply(stanza));
768 elseif child.name == "x" and child.attr.xmlns == "jabber:x:data" then
769 return self:process_form(origin, stanza);
771 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
776 function room_mt:handle_groupchat_to_room(origin, stanza)
777 -- Prosody has made the decision that messages with <subject/> are exclusively subject changes
778 -- e.g. body will be ignored; even if the subject change was not allowed
779 if stanza:get_child("subject") then
780 return module:fire_event("muc-subject-change", {room = self, origin = origin, stanza = stanza});
782 local from = stanza.attr.from;
783 local occupant = self:get_occupant_by_real_jid(from);
784 if not occupant then -- not in room
785 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
787 elseif occupant.role == "visitor" then
788 origin.send(st.error_reply(stanza, "auth", "forbidden"));
791 stanza.attr.from = occupant.nick;
792 self:broadcast_message(stanza);
793 stanza.attr.from = from;
797 -- hack - some buggy clients send presence updates to the room rather than their nick
798 function room_mt:handle_presence_to_room(origin, stanza)
799 local current_nick = self:get_occupant_jid(stanza.attr.from);
802 local to = stanza.attr.to;
803 stanza.attr.to = current_nick;
804 handled = self:handle_presence_to_occupant(origin, stanza);
810 -- Need visitor role or higher to invite
811 module:hook("muc-pre-invite", function(event)
812 local room, stanza = event.room, event.stanza;
813 local _from, _to = stanza.attr.from, stanza.attr.to;
814 local inviter = room:get_occupant_by_real_jid(_from);
815 local role = inviter and inviter.role or room:get_default_role(room:get_affiliation(_from));
816 if valid_roles[role or "none"] <= valid_roles.visitor then
817 event.origin.send(st.error_reply(stanza, "auth", "forbidden"));
822 function room_mt:handle_mediated_invite(origin, stanza)
823 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
824 local invitee = jid_prep(payload.attr.to);
826 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
828 elseif module:fire_event("muc-pre-invite", {room = self, origin = origin, stanza = stanza}) then
831 local invite = st.message({from = self.jid, to = invitee, id = stanza.attr.id})
832 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
833 :tag('invite', {from = stanza.attr.from;})
834 :tag('reason'):text(payload:get_child_text("reason")):up()
837 if not module:fire_event("muc-invite", {room = self, stanza = invite, origin = origin, incoming = stanza}) then
838 self:route_stanza(invite);
843 -- COMPAT: Some older clients expect this
844 module:hook("muc-invite", function(event)
845 local room, stanza = event.room, event.stanza;
846 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
847 local reason = invite:get_child_text("reason");
848 stanza:tag('x', {xmlns = "jabber:x:conference"; jid = room.jid;})
853 -- Add a plain message for clients which don't support invites
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") or "";
859 :text(invite.attr.from.." invited you to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
863 function room_mt:handle_mediated_decline(origin, stanza)
864 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
865 local declinee = jid_prep(payload.attr.to);
867 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
869 elseif module:fire_event("muc-pre-decline", {room = self, origin = origin, stanza = stanza}) then
872 local decline = st.message({from = self.jid, to = declinee, id = stanza.attr.id})
873 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
874 :tag("decline", {from = stanza.attr.from})
875 :tag("reason"):text(payload:get_child_text("reason")):up()
878 if not module:fire_event("muc-decline", {room = self, stanza = decline, origin = origin, incoming = stanza}) then
879 local occupant = self:get_occupant_by_real_jid(decline.attr.to);
881 self:route_to_occupant(occupant, decline);
883 self:route_stanza(decline);
889 -- Add a plain message for clients which don't support declines
890 module:hook("muc-decline", function(event)
891 local room, stanza = event.room, event.stanza;
892 local decline = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
893 local reason = decline:get_child_text("reason") or "";
895 :text(decline.attr.from.." declined your invite to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
899 function room_mt:handle_message_to_room(origin, stanza)
900 local type = stanza.attr.type;
901 if type == "groupchat" then
902 return self:handle_groupchat_to_room(origin, stanza)
903 elseif type == "error" and is_kickable_error(stanza) then
904 return self:handle_kickable(origin, stanza)
905 elseif type == nil then
906 local x = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
908 local payload = x.tags[1];
909 if payload == nil then
911 elseif payload.name == "invite" and payload.attr.to then
912 return self:handle_mediated_invite(origin, stanza)
913 elseif payload.name == "decline" and payload.attr.to then
914 return self:handle_mediated_decline(origin, stanza)
916 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
922 function room_mt:route_stanza(stanza)
926 function room_mt:get_affiliation(jid)
927 local node, host, resource = jid_split(jid);
928 local bare = node and node.."@"..host or host;
929 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
930 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
934 function room_mt:set_affiliation(actor, jid, affiliation, reason)
935 if not actor then return nil, "modify", "not-acceptable"; end;
939 if valid_affiliations[affiliation or "none"] == nil then
940 return nil, "modify", "not-acceptable";
942 affiliation = affiliation ~= "none" and affiliation or nil; -- coerces `affiliation == false` to `nil`
944 local target_affiliation = self._affiliations[jid]; -- Raw; don't want to check against host
945 local is_downgrade = valid_affiliations[target_affiliation or "none"] > valid_affiliations[affiliation or "none"];
947 if actor ~= true then
948 local actor_bare = jid_bare(actor);
949 local actor_affiliation = self._affiliations[actor_bare];
950 if actor_affiliation == "owner" then
951 if actor_bare == jid then -- self change
952 -- need at least one owner
953 local is_last = true;
954 for j, aff in pairs(self._affiliations) do if j ~= jid and aff == "owner" then is_last = false; break; end end
956 return nil, "cancel", "conflict";
959 -- owners can do anything else
960 elseif affiliation == "owner" or affiliation == "admin"
961 or actor_affiliation ~= "admin"
962 or target_affiliation == "owner" or target_affiliation == "admin" then
963 -- Can't demote owners or other admins
964 return nil, "cancel", "not-allowed";
969 self._affiliations[jid] = affiliation;
972 local role = self:get_default_role(affiliation);
973 local role_rank = valid_roles[role or "none"];
974 local occupants_updated = {}; -- Filled with old roles
975 for nick, occupant in self:each_occupant() do
976 if occupant.bare_jid == jid then
977 -- need to publcize in all cases; as affiliation in <item/> has changed.
978 occupants_updated[occupant] = occupant.role;
979 if occupant.role ~= role and (
981 valid_roles[occupant.role or "none"] < role_rank -- upgrade
983 occupant.role = role;
984 self:save_occupant(occupant);
989 -- Tell the room of the new occupant affiliations+roles
990 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
991 if not role then -- getting kicked
992 if affiliation == "outcast" then
993 x:tag("status", {code="301"}):up(); -- banned
995 x:tag("status", {code="321"}):up(); -- affiliation change
998 local is_semi_anonymous = self:get_whois() == "moderators";
999 for occupant, old_role in pairs(occupants_updated) do
1000 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1001 if is_semi_anonymous and
1002 (old_role == "moderator" and occupant.role ~= "moderator") or
1003 (old_role ~= "moderator" and occupant.role == "moderator") then -- Has gained or lost moderator status
1004 -- Send everyone else's presences (as jid visibility has changed)
1005 for real_jid in occupant:each_session() do
1006 self:send_occupant_list(real_jid, function(occupant_jid, occupant)
1007 return occupant.bare_jid ~= jid;
1013 if self.save then self:save(); end
1017 function room_mt:get_role(nick)
1018 local occupant = self:get_occupant_by_nick(nick);
1019 return occupant and occupant.role or nil;
1022 function room_mt:set_role(actor, occupant_jid, role, reason)
1023 if not actor then return nil, "modify", "not-acceptable"; end
1025 local occupant = self:get_occupant_by_nick(occupant_jid);
1026 if not occupant then return nil, "modify", "not-acceptable"; end
1028 if valid_roles[role or "none"] == nil then
1029 return nil, "modify", "not-acceptable";
1031 role = role ~= "none" and role or nil; -- coerces `role == false` to `nil`
1033 if actor ~= true then
1034 -- Can't do anything to other owners or admins
1035 local occupant_affiliation = self:get_affiliation(occupant.bare_jid);
1036 if occupant_affiliation == "owner" and occupant_affiliation == "admin" then
1037 return nil, "cancel", "not-allowed";
1040 -- If you are trying to give or take moderator role you need to be an owner or admin
1041 if occupant.role == "moderator" or role == "moderator" then
1042 local actor_affiliation = self:get_affiliation(actor);
1043 if actor_affiliation ~= "owner" and actor_affiliation ~= "admin" then
1044 return nil, "cancel", "not-allowed";
1048 -- Need to be in the room and a moderator
1049 local actor_occupant = self:get_occupant_by_real_jid(actor);
1050 if not actor_occupant or actor_occupant.role ~= "moderator" then
1051 return nil, "cancel", "not-allowed";
1055 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1057 x:tag("status", {code = "307"}):up();
1059 occupant.role = role;
1060 self:save_occupant(occupant);
1061 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1065 local name = module:require "muc/name";
1066 room_mt.get_name = name.get;
1067 room_mt.set_name = name.set;
1069 local description = module:require "muc/description";
1070 room_mt.get_description = description.get;
1071 room_mt.set_description = description.set;
1073 local hidden = module:require "muc/hidden";
1074 room_mt.get_hidden = hidden.get;
1075 room_mt.set_hidden = hidden.set;
1076 function room_mt:get_public()
1077 return not self:get_hidden();
1079 function room_mt:set_public(public)
1080 return self:set_hidden(not public);
1083 local password = module:require "muc/password";
1084 room_mt.get_password = password.get;
1085 room_mt.set_password = password.set;
1087 local whois = module:require "muc/whois";
1088 room_mt.get_whois = whois.get;
1089 room_mt.set_whois = whois.set;
1091 local members_only = module:require "muc/members_only";
1092 room_mt.get_members_only = members_only.get;
1093 room_mt.set_members_only = members_only.set;
1095 local moderated = module:require "muc/moderated";
1096 room_mt.get_moderated = moderated.get;
1097 room_mt.set_moderated = moderated.set;
1099 local persistent = module:require "muc/persistent";
1100 room_mt.get_persistent = persistent.get;
1101 room_mt.set_persistent = persistent.set;
1103 local subject = module:require "muc/subject";
1104 room_mt.get_changesubject = subject.get_changesubject;
1105 room_mt.set_changesubject = subject.set_changesubject;
1106 room_mt.get_subject = subject.get;
1107 room_mt.set_subject = subject.set;
1108 room_mt.send_subject = subject.send;
1110 local history = module:require "muc/history";
1111 room_mt.send_history = history.send;
1112 room_mt.get_historylength = history.get_length;
1113 room_mt.set_historylength = history.set_length;
1115 local _M = {}; -- module "muc"
1117 function _M.new_room(jid, config)
1118 return setmetatable({
1128 _M.room_mt = room_mt;