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:get_occupant_by_real_jid(real_jid)
83 local occupant_jid = self:get_occupant_jid(real_jid);
84 if occupant_jid == nil then return nil end
85 return self:get_occupant_by_nick(occupant_jid);
88 function room_mt:save_occupant(occupant)
89 occupant = occupant_lib.copy(occupant); -- So that occupant can be modified more
90 local id = occupant.nick
92 -- Need to maintain _jid_nick secondary index
93 local old_occupant = self._occupants[id];
95 for real_jid in pairs(old_occupant.sessions) do
96 self._jid_nick[real_jid] = nil;
99 if occupant.role ~= nil and next(occupant.sessions) then
100 for real_jid, presence in occupant:each_session() do
101 self._jid_nick[real_jid] = occupant.nick;
106 self._occupants[id] = occupant
109 function room_mt:route_to_occupant(occupant, stanza)
110 local to = stanza.attr.to;
111 for jid, pr in occupant:each_session() do
112 if pr.attr.type ~= "unavailable" then
113 stanza.attr.to = jid;
114 self:route_stanza(stanza);
120 -- actor is the attribute table
121 local function add_item(x, affiliation, role, jid, nick, actor, reason)
122 x:tag("item", {affiliation = affiliation; role = role; jid = jid; nick = nick;})
124 x:tag("actor", actor):up()
127 x:tag("reason"):text(reason):up()
133 -- actor is (real) jid
134 function room_mt:build_item_list(occupant, x, is_anonymous, nick, actor, reason)
135 local affiliation = self:get_affiliation(occupant.bare_jid) or "none";
136 local role = occupant.role or "none";
139 actor_attr = {nick = select(3,jid_split(self:get_occupant_jid(actor)))};
142 add_item(x, affiliation, role, nil, nick, actor_attr, reason);
145 actor_attr.jid = actor;
147 for real_jid, session in occupant:each_session() do
148 add_item(x, affiliation, role, real_jid, nick, actor_attr, reason);
154 function room_mt:broadcast_message(stanza)
155 module:fire_event("muc-broadcast-message", {room = self, stanza = stanza});
156 self:broadcast(stanza);
159 -- Broadcast a stanza to all occupants in the room.
160 -- optionally checks conditional called with (nick, occupant)
161 function room_mt:broadcast(stanza, cond_func)
162 for nick, occupant in self:each_occupant() do
163 if cond_func == nil or cond_func(nick, occupant) then
164 self:route_to_occupant(occupant, stanza)
169 local function can_see_real_jids(whois, occupant)
170 if whois == "anyone" then
172 elseif whois == "moderators" then
173 return valid_roles[occupant.role or "none"] >= valid_roles.moderator;
177 local function get_base_presence(occupant)
178 if occupant.role ~= nil then
179 -- Try to use main jid's presence
180 local pr = occupant:get_presence();
185 return st.presence {from = occupant.nick; type = "unavailable";};
188 -- Broadcasts an occupant's presence to the whole room
189 -- Takes the x element that goes into the stanzas
190 function room_mt:publicise_occupant_status(occupant, base_x, nick, actor, reason)
191 -- Build real jid and (optionally) occupant jid template presences
192 local function get_presence(is_anonymous)
193 local x = st.clone(base_x);
194 self:build_item_list(occupant, x, is_anonymous, nick, actor, reason);
195 return get_base_presence(occupant):add_child(x), x;
197 local full_p, full_x = get_presence(false);
198 local anon_p, anon_x;
199 local function get_anon_p()
200 if anon_p == nil then
201 anon_p, anon_x = get_presence(true);
203 return anon_p, anon_x;
206 local whois = self:get_whois();
209 for nick, n_occupant in self:each_occupant() do
210 if nick ~= occupant.nick then
212 if can_see_real_jids(whois, occupant) or occupant.bare_jid == n_occupant.bare_jid then
217 self:route_to_occupant(n_occupant, pr);
221 -- Presences for occupant itself
222 full_x:tag("status", {code = "110";}):up();
223 if occupant.role == nil then
224 -- They get an unavailable
225 self:route_to_occupant(occupant, full_p);
227 -- use their own presences as templates
228 for full_jid, pr in occupant:each_session() do
230 pr.attr.to = full_jid;
231 -- You can always see your own full jids
232 pr:add_child(full_x);
233 self:route_stanza(pr);
238 function room_mt:send_occupant_list(to, filter)
239 local to_bare = jid_bare(to);
240 local is_anonymous = true;
241 local whois = self:get_whois();
242 if whois ~= "anyone" then
243 local affiliation = self:get_affiliation(to);
244 if affiliation ~= "admin" and affiliation ~= "owner" then
245 local occupant = self:get_occupant_by_real_jid(to);
246 if not occupant or can_see_real_jids(whois, occupant) then
247 is_anonymous = false;
251 for occupant_jid, occupant in self:each_occupant() do
252 if filter == nil or filter(occupant_jid, occupant) then
253 local x = st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
254 self:build_item_list(occupant, x, is_anonymous and to_bare ~= occupant.bare_jid); -- can always see your own jids
255 local pres = st.clone(occupant:get_presence());
258 self:route_stanza(pres);
263 function room_mt:get_disco_info(stanza)
264 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#info");
265 local form = dataform.new {
266 { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" };
268 module:fire_event("muc-disco#info", {room = self; reply = reply; form = form;});
269 reply:add_child(form:form(nil, "result"));
272 module:hook("muc-disco#info", function(event)
273 event.reply:tag("feature", {var = "http://jabber.org/protocol/muc"}):up();
275 module:hook("muc-disco#info", function(event)
276 local count = iterators.count(event.room:each_occupant());
277 table.insert(event.form, { name = "muc#roominfo_occupants", label = "Number of occupants", value = tostring(count) });
280 function room_mt:get_disco_items(stanza)
281 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
282 for room_jid in self:each_occupant() do
283 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
288 function room_mt:handle_kickable(origin, stanza)
289 local real_jid = stanza.attr.from;
290 local occupant = self:get_occupant_by_real_jid(real_jid);
291 if occupant == nil then return nil; end
292 local type, condition, text = stanza:get_error();
293 local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
295 error_message = error_message..": "..text;
297 occupant:set_session(real_jid, st.presence({type="unavailable"})
298 :tag('status'):text(error_message));
299 self:save_occupant(occupant);
300 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
301 :tag("status", {code = "307"})
302 self:publicise_occupant_status(occupant, x);
306 -- Give the room creator owner affiliation
307 module:hook("muc-room-pre-create", function(event)
308 event.room:set_affiliation(true, jid_bare(event.stanza.attr.from), "owner");
311 -- check if user is banned
312 module:hook("muc-occupant-pre-join", function(event)
313 local room, stanza = event.room, event.stanza;
314 local affiliation = room:get_affiliation(stanza.attr.from);
315 if affiliation == "outcast" then
316 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
317 reply.tags[1].attr.code = "403";
318 event.origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
323 function room_mt:handle_presence_to_occupant(origin, stanza)
324 local type = stanza.attr.type;
325 if type == "error" then -- error, kick em out!
326 return self:handle_kickable(origin, stanza)
327 elseif type == nil or type == "unavailable" then
328 local real_jid = stanza.attr.from;
329 local bare_jid = jid_bare(real_jid);
330 local orig_occupant, dest_occupant;
331 local is_new_room = next(self._affiliations) == nil;
333 if type == "unavailable" then return true; end -- Unavailable from someone not in the room
334 if module:fire_event("muc-room-pre-create", {
338 }) then return true; end
340 orig_occupant = self:get_occupant_by_real_jid(real_jid);
341 if type == "unavailable" and orig_occupant == nil then return true; end -- Unavailable from someone not in the room
343 local is_first_dest_session;
344 if type == "unavailable" then
345 -- dest_occupant = nil
346 elseif orig_occupant and orig_occupant.nick == stanza.attr.to then -- Just a presence update
347 log("debug", "presence update for %s from session %s", orig_occupant.nick, real_jid);
348 dest_occupant = orig_occupant;
350 local dest_jid = stanza.attr.to;
351 dest_occupant = self:get_occupant_by_nick(dest_jid);
352 if dest_occupant == nil then
353 log("debug", "no occupant found for %s; creating new occupant object for %s", dest_jid, real_jid);
354 is_first_dest_session = true;
355 dest_occupant = self:new_occupant(bare_jid, dest_jid);
357 is_first_dest_session = false;
360 local is_last_orig_session;
361 if orig_occupant ~= nil then
362 -- Is there are least 2 sessions?
363 local iter, ob, last = orig_occupant:each_session();
364 is_last_orig_session = iter(ob, iter(ob, last)) == nil;
367 local event, event_name = {
371 is_first_session = is_first_dest_session;
372 is_last_session = is_last_orig_session;
374 if orig_occupant == nil then
375 event_name = "muc-occupant-pre-join";
376 event.is_new_room = is_new_room;
377 elseif dest_occupant == nil then
378 event_name = "muc-occupant-pre-leave";
380 event_name = "muc-occupant-pre-change";
382 if module:fire_event(event_name, event) then return true; end
384 -- Check for nick conflicts
385 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
386 log("debug", "%s couldn't join due to nick conflict: %s", real_jid, dest_occupant.nick);
387 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
388 reply.tags[1].attr.code = "409";
389 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
393 -- Send presence stanza about original occupant
394 if orig_occupant ~= nil and orig_occupant ~= dest_occupant then
395 local orig_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
397 if dest_occupant == nil then -- Session is leaving
398 log("debug", "session %s is leaving occupant %s", real_jid, orig_occupant.nick);
399 orig_occupant.role = nil;
400 orig_occupant:set_session(real_jid, stanza);
402 log("debug", "session %s is changing from occupant %s to %s", real_jid, orig_occupant.nick, dest_occupant.nick);
403 local generated_unavail = st.presence {from = orig_occupant.nick, to = real_jid, type = "unavailable"};
404 orig_occupant:set_session(real_jid, generated_unavail);
405 dest_nick = select(3, jid_split(dest_occupant.nick));
406 if not is_first_dest_session then -- User is swapping into another pre-existing session
407 log("debug", "session %s is swapping into multisession %s, showing it leave.", real_jid, dest_occupant.nick);
408 -- Show the other session leaving
409 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
410 :tag("status"):text("you are joining pre-existing session " .. dest_nick):up();
411 add_item(x, self:get_affiliation(bare_jid), "none");
412 local pr = st.presence{from = dest_occupant.nick, to = real_jid, type = "unavailable"}
414 self:route_stanza(pr);
416 if is_first_dest_session and is_last_orig_session then -- Normal nick change
417 log("debug", "no sessions in %s left; publically marking as nick change", orig_occupant.nick);
418 orig_x:tag("status", {code = "303";}):up();
419 else -- The session itself always needs to see a nick change
420 -- don't want to get our old nick's available presence,
421 -- so remove our session from there, and manually generate an unavailable
422 orig_occupant:remove_session(real_jid);
423 log("debug", "generating nick change for %s", real_jid);
424 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
425 -- self:build_item_list(orig_occupant, x, false, dest_nick); -- COMPAT: clients get confused if they see other items besides their own
426 add_item(x, self:get_affiliation(bare_jid), orig_occupant.role, real_jid, dest_nick);
427 x:tag("status", {code = "303";}):up();
428 x:tag("status", {code = "110";}):up();
429 self:route_stanza(generated_unavail:add_child(x));
430 dest_nick = nil; -- set dest_nick to nil; so general populance doesn't see it for whole orig_occupant
433 self:save_occupant(orig_occupant);
434 self:publicise_occupant_status(orig_occupant, orig_x, dest_nick);
436 if is_last_orig_session then
437 module:fire_event("muc-occupant-left", {room = self; nick = orig_occupant.nick;});
441 if dest_occupant ~= nil then
442 dest_occupant:set_session(real_jid, stanza);
443 local dest_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
445 dest_x:tag("status", {code = "201"}):up();
447 if orig_occupant == nil and self:get_whois() == "anyone" then
448 dest_x:tag("status", {code = "100"}):up();
450 self:save_occupant(dest_occupant);
452 if orig_occupant == nil and is_first_dest_session then
453 -- Send occupant list to newly joined user
454 self:send_occupant_list(real_jid, function(nick, occupant)
455 -- Don't include self
456 return occupant:get_presence(real_jid) == nil;
459 self:publicise_occupant_status(dest_occupant, dest_x);
461 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
462 log("debug", "session %s split nicks; showing %s rejoining", real_jid, orig_occupant.nick);
463 -- Show the original nick joining again
464 local pr = st.clone(orig_occupant:get_presence());
465 pr.attr.to = real_jid;
466 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
467 self:build_item_list(orig_occupant, x, false);
468 -- TODO: new status code to inform client this was the multi-session it left?
470 self:route_stanza(pr);
473 if orig_occupant == nil and is_first_dest_session then
474 module:fire_event("muc-occupant-joined", {room = self; nick = dest_occupant.nick; stanza = stanza;});
477 elseif type ~= 'result' then -- bad type
478 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
479 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
485 function room_mt:handle_iq_to_occupant(origin, stanza)
486 local from, to = stanza.attr.from, stanza.attr.to;
487 local type = stanza.attr.type;
488 local id = stanza.attr.id;
489 local occupant = self:get_occupant_by_nick(to);
490 if (type == "error" or type == "result") then
491 do -- deconstruct_stanza_id
492 if not occupant then return nil; end
493 local from_jid, id, to_jid_hash = (base64.decode(stanza.attr.id) or ""):match("^(.+)%z(.*)%z(.+)$");
494 if not(from == from_jid or from == jid_bare(from_jid)) then return nil; end
495 local from_occupant_jid = self:get_occupant_jid(from_jid);
496 if from_occupant_jid == nil then return nil; end
498 for to_jid in occupant:each_session() do
499 if md5(to_jid) == to_jid_hash then
500 session_jid = to_jid;
504 if session_jid == nil then return nil; end
505 stanza.attr.from, stanza.attr.to, stanza.attr.id = from_jid, session_jid, id;
507 log("debug", "%s sent private iq stanza to %s (%s)", from, to, stanza.attr.to);
508 self:route_stanza(stanza);
509 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
511 else -- Type is "get" or "set"
512 local current_nick = self:get_occupant_jid(from);
513 if not current_nick then
514 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
517 if not occupant then -- recipient not in room
518 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
521 do -- construct_stanza_id
522 stanza.attr.id = base64.encode(occupant.jid.."\0"..stanza.attr.id.."\0"..md5(from));
524 stanza.attr.from, stanza.attr.to = current_nick, occupant.jid;
525 log("debug", "%s sent private iq stanza to %s (%s)", from, to, occupant.jid);
526 if stanza.tags[1].attr.xmlns == 'vcard-temp' then
527 stanza.attr.to = jid_bare(stanza.attr.to);
529 self:route_stanza(stanza);
530 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
535 function room_mt:handle_message_to_occupant(origin, stanza)
536 local from, to = stanza.attr.from, stanza.attr.to;
537 local current_nick = self:get_occupant_jid(from);
538 local type = stanza.attr.type;
539 if not current_nick then -- not in room
540 if type ~= "error" then
541 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
545 if type == "groupchat" then -- groupchat messages not allowed in PM
546 origin.send(st.error_reply(stanza, "modify", "bad-request"));
548 elseif type == "error" and is_kickable_error(stanza) then
549 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
550 return self:handle_kickable(origin, stanza); -- send unavailable
553 local o_data = self:get_occupant_by_nick(to);
555 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
558 log("debug", "%s sent private message stanza to %s (%s)", from, to, o_data.jid);
559 stanza:tag("x", { xmlns = "http://jabber.org/protocol/muc#user" }):up();
560 stanza.attr.from = current_nick;
561 self:route_to_occupant(o_data, stanza)
562 -- TODO: Remove x tag?
563 stanza.attr.from = from;
567 function room_mt:send_form(origin, stanza)
568 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
569 :add_child(self:get_form_layout(stanza.attr.from):form())
573 function room_mt:get_form_layout(actor)
574 local form = dataform.new({
575 title = "Configuration for "..self.jid,
576 instructions = "Complete and submit this form to configure the room.",
580 value = 'http://jabber.org/protocol/muc#roomconfig'
583 return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
586 function room_mt:process_form(origin, stanza)
587 local form = stanza.tags[1]:get_child("x", "jabber:x:data");
588 if form.attr.type == "cancel" then
589 origin.send(st.reply(stanza));
590 elseif form.attr.type == "submit" then
591 local fields = self:get_form_layout(stanza.attr.from):data(form);
592 if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then
593 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration"));
597 local event = {room = self; origin = origin; stanza = stanza; fields = fields; status_codes = {};};
598 function event.update_option(name, field, allowed)
599 local new = fields[field];
600 if new == nil then return; end
601 if allowed and not allowed[new] then return; end
602 if new == self["get_"..name](self) then return; end
603 event.status_codes["104"] = true;
604 self["set_"..name](self, new);
607 module:fire_event("muc-config-submitted", event);
609 if self.save then self:save(true); end
610 origin.send(st.reply(stanza));
612 if next(event.status_codes) then
613 local msg = st.message({type='groupchat', from=self.jid})
614 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
615 for code in pairs(event.status_codes) do
616 msg:tag("status", {code = code;}):up();
619 self:broadcast_message(msg);
622 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form"));
627 -- Removes everyone from the room
628 function room_mt:clear(x)
629 x = x or st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
630 local occupants_updated = {};
631 for nick, occupant in self:each_occupant() do
633 self:save_occupant(occupant);
634 occupants_updated[occupant] = true;
636 for occupant in pairs(occupants_updated) do
637 self:publicise_occupant_status(occupant, x);
638 module:fire_event("muc-occupant-left", { room = self; nick = occupant.nick; });
642 function room_mt:destroy(newjid, reason, password)
643 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
644 :tag("item", { affiliation='none', role='none' }):up()
645 :tag("destroy", {jid=newjid});
646 if reason then x:tag("reason"):text(reason):up(); end
647 if password then x:tag("password"):text(password):up(); end
650 module:fire_event("muc-room-destroyed", { room = self });
653 function room_mt:handle_disco_info_get_query(origin, stanza)
654 origin.send(self:get_disco_info(stanza));
658 function room_mt:handle_disco_items_get_query(origin, stanza)
659 origin.send(self:get_disco_items(stanza));
663 function room_mt:handle_admin_query_set_command(origin, stanza)
664 local item = stanza.tags[1].tags[1];
665 if item.attr.jid then -- Validate provided JID
666 item.attr.jid = jid_prep(item.attr.jid);
667 if not item.attr.jid then
668 origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
672 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
673 local occupant = self:get_occupant_by_nick(self.jid.."/"..item.attr.nick);
674 if occupant then item.attr.jid = occupant.jid; end
675 elseif not item.attr.nick and item.attr.jid then
676 local nick = self:get_occupant_jid(item.attr.jid);
677 if nick then item.attr.nick = select(3, jid_split(nick)); end
679 local actor = stanza.attr.from;
680 local reason = item:get_child_text("reason");
681 local success, errtype, err
682 if item.attr.affiliation and item.attr.jid and not item.attr.role then
683 success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, reason);
684 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
685 success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, reason);
687 success, errtype, err = nil, "cancel", "bad-request";
689 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
690 origin.send(st.reply(stanza));
694 function room_mt:handle_admin_query_get_command(origin, stanza)
695 local actor = stanza.attr.from;
696 local affiliation = self:get_affiliation(actor);
697 local item = stanza.tags[1].tags[1];
698 local _aff = item.attr.affiliation;
699 local _rol = item.attr.role;
700 if _aff and not _rol then
701 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
702 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
703 for jid, affiliation in pairs(self._affiliations) do
704 if affiliation == _aff then
705 reply:tag("item", {affiliation = _aff, jid = jid}):up();
711 origin.send(st.error_reply(stanza, "auth", "forbidden"));
714 elseif _rol and not _aff then
715 local role = self:get_role(self:get_occupant_jid(actor)) or self:get_default_role(affiliation);
716 if valid_roles[role or "none"] >= valid_roles.moderator then
717 if _rol == "none" then _rol = nil; end
718 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
719 -- TODO: whois check here? (though fully anonymous rooms are not supported)
720 for occupant_jid, occupant in self:each_occupant() do
721 if occupant.role == _rol then
722 local nick = select(3,jid_split(occupant_jid));
723 self:build_item_list(occupant, reply, false, nick);
726 origin.send(reply:up());
729 origin.send(st.error_reply(stanza, "auth", "forbidden"));
733 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
738 function room_mt:handle_owner_query_get_to_room(origin, stanza)
739 if self:get_affiliation(stanza.attr.from) ~= "owner" then
740 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
744 self:send_form(origin, stanza);
747 function room_mt:handle_owner_query_set_to_room(origin, stanza)
748 if self:get_affiliation(stanza.attr.from) ~= "owner" then
749 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
753 local child = stanza.tags[1].tags[1];
755 origin.send(st.error_reply(stanza, "modify", "bad-request"));
757 elseif child.name == "destroy" then
758 local newjid = child.attr.jid;
759 local reason = child:get_child_text("reason");
760 local password = child:get_child_text("password");
761 self:destroy(newjid, reason, password);
762 origin.send(st.reply(stanza));
764 elseif child.name == "x" and child.attr.xmlns == "jabber:x:data" then
765 return self:process_form(origin, stanza);
767 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
772 function room_mt:handle_groupchat_to_room(origin, stanza)
773 -- Prosody has made the decision that messages with <subject/> are exclusively subject changes
774 -- e.g. body will be ignored; even if the subject change was not allowed
775 if stanza:get_child("subject") then
776 return module:fire_event("muc-subject-change", {room = self, origin = origin, stanza = stanza});
778 local from = stanza.attr.from;
779 local occupant = self:get_occupant_by_real_jid(from);
780 if not occupant then -- not in room
781 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
783 elseif occupant.role == "visitor" then
784 origin.send(st.error_reply(stanza, "auth", "forbidden"));
787 stanza.attr.from = occupant.nick;
788 self:broadcast_message(stanza);
789 stanza.attr.from = from;
793 -- hack - some buggy clients send presence updates to the room rather than their nick
794 function room_mt:handle_presence_to_room(origin, stanza)
795 local current_nick = self:get_occupant_jid(stanza.attr.from);
798 local to = stanza.attr.to;
799 stanza.attr.to = current_nick;
800 handled = self:handle_presence_to_occupant(origin, stanza);
806 -- Need visitor role or higher to invite
807 module:hook("muc-pre-invite", function(event)
808 local room, stanza = event.room, event.stanza;
809 local _from, _to = stanza.attr.from, stanza.attr.to;
810 local inviter = room:get_occupant_by_real_jid(_from);
811 local role = inviter and inviter.role or room:get_default_role(room:get_affiliation(_from));
812 if valid_roles[role or "none"] <= valid_roles.visitor then
813 event.origin.send(st.error_reply(stanza, "auth", "forbidden"));
818 function room_mt:handle_mediated_invite(origin, stanza)
819 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
820 local invitee = jid_prep(payload.attr.to);
822 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
824 elseif module:fire_event("muc-pre-invite", {room = self, origin = origin, stanza = stanza}) then
827 local invite = st.message({from = self.jid, to = invitee, id = stanza.attr.id})
828 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
829 :tag('invite', {from = stanza.attr.from;})
830 :tag('reason'):text(payload:get_child_text("reason")):up()
833 if not module:fire_event("muc-invite", {room = self, stanza = invite, origin = origin, incoming = stanza}) then
834 self:route_stanza(invite);
839 -- COMPAT: Some older clients expect this
840 module:hook("muc-invite", function(event)
841 local room, stanza = event.room, event.stanza;
842 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
843 local reason = invite:get_child_text("reason");
844 stanza:tag('x', {xmlns = "jabber:x:conference"; jid = room.jid;})
849 -- Add a plain message for clients which don't support invites
850 module:hook("muc-invite", function(event)
851 local room, stanza = event.room, event.stanza;
852 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
853 local reason = invite:get_child_text("reason") or "";
855 :text(invite.attr.from.." invited you to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
859 function room_mt:handle_mediated_decline(origin, stanza)
860 local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
861 local declinee = jid_prep(payload.attr.to);
863 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
865 elseif module:fire_event("muc-pre-decline", {room = self, origin = origin, stanza = stanza}) then
868 local decline = st.message({from = self.jid, to = declinee, id = stanza.attr.id})
869 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
870 :tag("decline", {from = stanza.attr.from})
871 :tag("reason"):text(payload:get_child_text("reason")):up()
874 if not module:fire_event("muc-decline", {room = self, stanza = decline, origin = origin, incoming = stanza}) then
875 local occupant = self:get_occupant_by_real_jid(decline.attr.to);
877 self:route_to_occupant(occupant, decline);
879 self:route_stanza(decline);
885 -- Add a plain message for clients which don't support declines
886 module:hook("muc-decline", function(event)
887 local room, stanza = event.room, event.stanza;
888 local decline = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
889 local reason = decline:get_child_text("reason") or "";
891 :text(decline.attr.from.." declined your invite to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
895 function room_mt:handle_message_to_room(origin, stanza)
896 local type = stanza.attr.type;
897 if type == "groupchat" then
898 return self:handle_groupchat_to_room(origin, stanza)
899 elseif type == "error" and is_kickable_error(stanza) then
900 return self:handle_kickable(origin, stanza)
901 elseif type == nil then
902 local x = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
904 local payload = x.tags[1];
905 if payload == nil then
907 elseif payload.name == "invite" and payload.attr.to then
908 return self:handle_mediated_invite(origin, stanza)
909 elseif payload.name == "decline" and payload.attr.to then
910 return self:handle_mediated_decline(origin, stanza)
912 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
918 function room_mt:route_stanza(stanza)
922 function room_mt:get_affiliation(jid)
923 local node, host, resource = jid_split(jid);
924 local bare = node and node.."@"..host or host;
925 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
926 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
930 function room_mt:set_affiliation(actor, jid, affiliation, reason)
931 if not actor then return nil, "modify", "not-acceptable"; end;
935 if valid_affiliations[affiliation or "none"] == nil then
936 return nil, "modify", "not-acceptable";
938 affiliation = affiliation ~= "none" and affiliation or nil; -- coerces `affiliation == false` to `nil`
940 local target_affiliation = self._affiliations[jid]; -- Raw; don't want to check against host
941 local is_downgrade = valid_affiliations[target_affiliation or "none"] > valid_affiliations[affiliation or "none"];
943 if actor ~= true then
944 local actor_bare = jid_bare(actor);
945 local actor_affiliation = self._affiliations[actor_bare];
946 if actor_affiliation == "owner" then
947 if actor_bare == jid then -- self change
948 -- need at least one owner
949 local is_last = true;
950 for j, aff in pairs(self._affiliations) do if j ~= jid and aff == "owner" then is_last = false; break; end end
952 return nil, "cancel", "conflict";
955 -- owners can do anything else
956 elseif affiliation == "owner" or affiliation == "admin"
957 or actor_affiliation ~= "admin"
958 or target_affiliation == "owner" or target_affiliation == "admin" then
959 -- Can't demote owners or other admins
960 return nil, "cancel", "not-allowed";
965 self._affiliations[jid] = affiliation;
968 local role = self:get_default_role(affiliation);
969 local role_rank = valid_roles[role or "none"];
970 local occupants_updated = {}; -- Filled with old roles
971 for nick, occupant in self:each_occupant() do
972 if occupant.bare_jid == jid then
973 -- need to publcize in all cases; as affiliation in <item/> has changed.
974 occupants_updated[occupant] = occupant.role;
975 if occupant.role ~= role and (
977 valid_roles[occupant.role or "none"] < role_rank -- upgrade
979 occupant.role = role;
980 self:save_occupant(occupant);
985 -- Tell the room of the new occupant affiliations+roles
986 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
987 if not role then -- getting kicked
988 if affiliation == "outcast" then
989 x:tag("status", {code="301"}):up(); -- banned
991 x:tag("status", {code="321"}):up(); -- affiliation change
994 local is_semi_anonymous = self:get_whois() == "moderators";
995 for occupant, old_role in pairs(occupants_updated) do
996 self:publicise_occupant_status(occupant, x, nil, actor, reason);
997 if is_semi_anonymous and
998 (old_role == "moderator" and occupant.role ~= "moderator") or
999 (old_role ~= "moderator" and occupant.role == "moderator") then -- Has gained or lost moderator status
1000 -- Send everyone else's presences (as jid visibility has changed)
1001 for real_jid in occupant:each_session() do
1002 self:send_occupant_list(real_jid, function(occupant_jid, occupant)
1003 return occupant.bare_jid ~= jid;
1009 if self.save then self:save(); end
1013 function room_mt:get_role(nick)
1014 local occupant = self:get_occupant_by_nick(nick);
1015 return occupant and occupant.role or nil;
1018 function room_mt:set_role(actor, occupant_jid, role, reason)
1019 if not actor then return nil, "modify", "not-acceptable"; end
1021 local occupant = self:get_occupant_by_nick(occupant_jid);
1022 if not occupant then return nil, "modify", "not-acceptable"; end
1024 if valid_roles[role or "none"] == nil then
1025 return nil, "modify", "not-acceptable";
1027 role = role ~= "none" and role or nil; -- coerces `role == false` to `nil`
1029 if actor ~= true then
1030 -- Can't do anything to other owners or admins
1031 local occupant_affiliation = self:get_affiliation(occupant.bare_jid);
1032 if occupant_affiliation == "owner" and occupant_affiliation == "admin" then
1033 return nil, "cancel", "not-allowed";
1036 -- If you are trying to give or take moderator role you need to be an owner or admin
1037 if occupant.role == "moderator" or role == "moderator" then
1038 local actor_affiliation = self:get_affiliation(actor);
1039 if actor_affiliation ~= "owner" and actor_affiliation ~= "admin" then
1040 return nil, "cancel", "not-allowed";
1044 -- Need to be in the room and a moderator
1045 local actor_occupant = self:get_occupant_by_real_jid(actor);
1046 if not actor_occupant or actor_occupant.role ~= "moderator" then
1047 return nil, "cancel", "not-allowed";
1051 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1053 x:tag("status", {code = "307"}):up();
1055 occupant.role = role;
1056 self:save_occupant(occupant);
1057 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1061 local name = module:require "muc/name";
1062 room_mt.get_name = name.get;
1063 room_mt.set_name = name.set;
1065 local description = module:require "muc/description";
1066 room_mt.get_description = description.get;
1067 room_mt.set_description = description.set;
1069 local hidden = module:require "muc/hidden";
1070 room_mt.get_hidden = hidden.get;
1071 room_mt.set_hidden = hidden.set;
1072 function room_mt:get_public()
1073 return not self:get_hidden();
1075 function room_mt:set_public(public)
1076 return self:set_hidden(not public);
1079 local password = module:require "muc/password";
1080 room_mt.get_password = password.get;
1081 room_mt.set_password = password.set;
1083 local whois = module:require "muc/whois";
1084 room_mt.get_whois = whois.get;
1085 room_mt.set_whois = whois.set;
1087 local members_only = module:require "muc/members_only";
1088 room_mt.get_members_only = members_only.get;
1089 room_mt.set_members_only = members_only.set;
1091 local moderated = module:require "muc/moderated";
1092 room_mt.get_moderated = moderated.get;
1093 room_mt.set_moderated = moderated.set;
1095 local persistent = module:require "muc/persistent";
1096 room_mt.get_persistent = persistent.get;
1097 room_mt.set_persistent = persistent.set;
1099 local subject = module:require "muc/subject";
1100 room_mt.get_changesubject = subject.get_changesubject;
1101 room_mt.set_changesubject = subject.set_changesubject;
1102 room_mt.get_subject = subject.get;
1103 room_mt.set_subject = subject.set;
1104 room_mt.send_subject = subject.send;
1106 local history = module:require "muc/history";
1107 room_mt.send_history = history.send;
1108 room_mt.get_historylength = history.get_length;
1109 room_mt.set_historylength = history.set_length;
1111 local _M = {}; -- module "muc"
1113 _M.set_max_history_length = history.set_max_length;
1115 function _M.new_room(jid, config)
1116 return setmetatable({
1126 _M.room_mt = room_mt;