2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 Waqas Hussain
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
9 local datamanager = require "util.datamanager";
10 local datetime = require "util.datetime";
12 local jid_split = require "util.jid".split;
13 local jid_bare = require "util.jid".bare;
14 local jid_prep = require "util.jid".prep;
15 local st = require "util.stanza";
16 local log = require "util.logger".init("mod_muc");
17 local multitable_new = require "util.multitable".new;
18 local t_insert, t_remove = table.insert, table.remove;
19 local setmetatable = setmetatable;
20 local base64 = require "util.encodings".base64;
21 local md5 = require "util.hashes".md5;
23 local muc_domain = nil; --module:get_host();
24 local history_length = 20;
27 local function filter_xmlns_from_array(array, filters)
30 local attr = array[i].attr;
31 if filters[attr and attr.xmlns] then
38 local function filter_xmlns_from_stanza(stanza, filters)
40 if filter_xmlns_from_array(stanza.tags, filters) ~= 0 then
41 return stanza, filter_xmlns_from_array(stanza, filters);
46 local presence_filters = {["http://jabber.org/protocol/muc"]=true;["http://jabber.org/protocol/muc#user"]=true};
47 local function get_filtered_presence(stanza)
48 return filter_xmlns_from_stanza(st.clone(stanza):reset(), presence_filters);
50 local kickable_error_conditions = {
52 ["internal-server-error"] = true;
53 ["item-not-found"] = true;
54 ["jid-malformed"] = true;
55 ["recipient-unavailable"] = true;
57 ["remote-server-not-found"] = true;
58 ["remote-server-timeout"] = true;
59 ["service-unavailable"] = true;
60 ["malformed error"] = true;
62 local function get_error_condition(stanza)
63 for _, tag in ipairs(stanza.tags) do
64 if tag.name == "error" and (not(tag.attr.xmlns) or tag.attr.xmlns == "jabber:client") then
65 for _, cond in ipairs(tag.tags) do
66 if cond.attr.xmlns == "urn:ietf:params:xml:ns:xmpp-stanzas" then
70 return "malformed error";
73 return "malformed error";
75 local function is_kickable_error(stanza)
76 local cond = get_error_condition(stanza);
77 return kickable_error_conditions[cond] and cond;
79 local function getUsingPath(stanza, path, getText)
81 for _, name in ipairs(path) do
82 if type(tag) ~= 'table' then return; end
83 tag = tag:child_with_name(name);
85 if tag and getText then tag = table.concat(tag); end
88 local function getTag(stanza, path) return getUsingPath(stanza, path); end
89 local function getText(stanza, path) return getUsingPath(stanza, path, true); end
92 --[[function get_room_disco_info(room, stanza)
93 return st.iq({type='result', id=stanza.attr.id, from=stanza.attr.to, to=stanza.attr.from}):query("http://jabber.org/protocol/disco#info")
94 :tag("identity", {category='conference', type='text', name=room._data["name"]):up()
95 :tag("feature", {var="http://jabber.org/protocol/muc"}); -- TODO cache disco reply
97 function get_room_disco_items(room, stanza)
98 return st.iq({type='result', id=stanza.attr.id, from=stanza.attr.to, to=stanza.attr.from}):query("http://jabber.org/protocol/disco#items");
99 end -- TODO allow non-private rooms]]
104 room_mt.__index = room_mt;
106 function room_mt:get_default_role(affiliation)
107 if affiliation == "owner" or affiliation == "admin" then
109 elseif affiliation == "member" or not affiliation then
110 return "participant";
114 function room_mt:broadcast_presence(stanza, sid, code, nick)
115 stanza = get_filtered_presence(stanza);
116 local occupant = self._occupants[stanza.attr.from];
117 stanza:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
118 :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none", nick=nick}):up();
120 stanza:tag("status", {code=code}):up();
122 self:broadcast_except_nick(stanza, stanza.attr.from);
123 local me = self._occupants[stanza.attr.from];
125 stanza:tag("status", {code='110'});
126 stanza.attr.to = sid;
127 self:_route_stanza(stanza);
130 function room_mt:broadcast_message(stanza, historic)
131 local to = stanza.attr.to;
132 for occupant, o_data in pairs(self._occupants) do
133 for jid in pairs(o_data.sessions) do
134 stanza.attr.to = jid;
135 self:_route_stanza(stanza);
139 if historic then -- add to history
140 local history = self._data['history'];
141 if not history then history = {}; self._data['history'] = history; end
142 stanza = st.clone(stanza);
143 stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = muc_domain, stamp = datetime.datetime()}):up(); -- XEP-0203
144 stanza:tag("x", {xmlns = "jabber:x:delay", from = muc_domain, stamp = datetime.legacy()}):up(); -- XEP-0091 (deprecated)
145 t_insert(history, st.preserialize(stanza));
146 while #history > history_length do t_remove(history, 1) end
149 function room_mt:broadcast_except_nick(stanza, nick)
150 for rnick, occupant in pairs(self._occupants) do
151 if rnick ~= nick then
152 for jid in pairs(occupant.sessions) do
153 stanza.attr.to = jid;
154 self:_route_stanza(stanza);
160 function room_mt:send_occupant_list(to)
161 local current_nick = self._jid_nick[to];
162 for occupant, o_data in pairs(self._occupants) do
163 if occupant ~= current_nick then
164 local pres = get_filtered_presence(o_data.sessions[o_data.jid]);
165 pres.attr.to, pres.attr.from = to, occupant;
166 pres:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
167 :tag("item", {affiliation=o_data.affiliation or "none", role=o_data.role or "none"}):up();
168 self:_route_stanza(pres);
172 function room_mt:send_history(to)
173 local history = self._data['history']; -- send discussion history
175 for _, msg in ipairs(history) do
176 msg = st.deserialize(msg);
178 self:_route_stanza(msg);
181 if self._data['subject'] then
182 self:_route_stanza(st.message({type='groupchat', from=self.jid, to=to}):tag("subject"):text(self._data['subject']));
186 local function room_get_disco_info(self, stanza)
187 return st.reply(stanza):query("http://jabber.org/protocol/disco#info")
188 :tag("identity", {category="conference", type="text"}):up()
189 :tag("feature", {var="http://jabber.org/protocol/muc"});
191 local function room_get_disco_items(self, stanza)
192 local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
193 for room_jid in pairs(self._occupants) do
194 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
198 function room_mt:set_subject(current_nick, subject)
199 -- TODO check nick's authority
200 if subject == "" then subject = nil; end
201 self._data['subject'] = subject;
202 if self.save then self:save(); end
203 local msg = st.message({type='groupchat', from=current_nick})
204 :tag('subject'):text(subject):up();
205 self:broadcast_message(msg, false);
209 function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
210 local from, to = stanza.attr.from, stanza.attr.to;
211 local room = jid_bare(to);
212 local current_nick = self._jid_nick[from];
213 local type = stanza.attr.type;
214 log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
215 if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
216 if stanza.name == "presence" then
217 local pr = get_filtered_presence(stanza);
218 pr.attr.from = current_nick;
219 if type == "error" then -- error, kick em out!
221 log("debug", "kicking %s from %s", current_nick, room);
222 self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
223 :tag('status'):text('Kicked: '..get_error_condition(stanza))); -- send unavailable
225 elseif type == "unavailable" then -- unavailable
227 log("debug", "%s leaving %s", current_nick, room);
228 local occupant = self._occupants[current_nick];
229 local new_jid = next(occupant.sessions);
230 if new_jid == from then new_jid = next(occupant.sessions, new_jid); end
232 local jid = occupant.jid;
233 occupant.jid = new_jid;
234 occupant.sessions[from] = nil;
236 pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
237 :tag("item", {affiliation=occupant.affiliation or "none", role='none'}):up()
238 :tag("status", {code='110'});
239 self:_route_stanza(pr);
240 if jid ~= new_jid then
241 pr = st.clone(occupant.sessions[new_jid])
242 :tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
243 :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none"});
244 pr.attr.from = current_nick;
245 self:broadcast_except_nick(pr, current_nick);
248 occupant.role = 'none';
249 self:broadcast_presence(pr, from);
250 self._occupants[current_nick] = nil;
252 self._jid_nick[from] = nil;
254 elseif not type then -- available
256 --if #pr == #stanza or current_nick ~= to then -- commented because google keeps resending directed presence
257 if current_nick == to then -- simple presence
258 log("debug", "%s broadcasted presence", current_nick);
259 self._occupants[current_nick].sessions[from] = pr;
260 self:broadcast_presence(pr, from);
262 local occupant = self._occupants[current_nick];
263 local is_multisession = next(occupant.sessions, next(occupant.sessions));
264 if self._occupants[to] or is_multisession then
265 log("debug", "%s couldn't change nick", current_nick);
266 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
267 reply.tags[1].attr.code = "409";
268 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
270 local data = self._occupants[current_nick];
271 local to_nick = select(3, jid_split(to));
273 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
274 local p = st.presence({type='unavailable', from=current_nick});
275 self:broadcast_presence(p, from, '303', to_nick);
276 self._occupants[current_nick] = nil;
277 self._occupants[to] = data;
278 self._jid_nick[from] = to;
280 self._occupants[to].sessions[from] = pr;
281 self:broadcast_presence(pr, from);
287 --else -- possible rejoin
288 -- log("debug", "%s had connection replaced", current_nick);
289 -- self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
290 -- :tag('status'):text('Replaced by new connection'):up()); -- send unavailable
291 -- self:handle_to_occupant(origin, stanza); -- resend available
296 if self._occupants[to] then
297 if jid_bare(from) ~= jid_bare(self._occupants[to].jid) then
303 log("debug", "%s couldn't join due to nick conflict: %s", from, to);
304 local reply = st.error_reply(stanza, "cancel", "conflict"):up();
305 reply.tags[1].attr.code = "409";
306 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
308 log("debug", "%s joining as %s", from, to);
309 if not next(self._affiliations) then -- new room, no owners
310 self._affiliations[jid_bare(from)] = "owner";
312 local affiliation = self:get_affiliation(from);
313 local role = self:get_default_role(affiliation)
314 if role then -- new occupant
316 self._occupants[to] = {affiliation=affiliation, role=role, jid=from, sessions={[from]=get_filtered_presence(stanza)}};
318 self._occupants[to].sessions[from] = get_filtered_presence(stanza);
320 self._jid_nick[from] = to;
321 self:send_occupant_list(from);
324 self:broadcast_presence(pr, from);
327 self:_route_stanza(pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
328 :tag("item", {affiliation=affiliation or "none", role=role or "none"}):up()
329 :tag("status", {code='110'}));
331 self:send_history(from);
333 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
334 reply.tags[1].attr.code = "403";
335 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
339 elseif type ~= 'result' then -- bad type
340 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
341 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
344 elseif not current_nick then -- not in room
345 if type == "error" or type == "result" then
346 local id = stanza.name == "iq" and stanza.attr.id and base64.decode(stanza.attr.id);
347 local _nick, _id, _hash = (id or ""):match("^(.+)%z(.*)%z(.+)$");
348 local occupant = self._occupants[stanza.attr.to];
349 if occupant and _nick and self._jid_nick[_nick] and _id and _hash then
350 local id, _to = stanza.attr.id;
351 for jid in pairs(occupant.sessions) do
352 if md5(jid) == _hash then
358 stanza.attr.to, stanza.attr.from, stanza.attr.id = _to, self._jid_nick[_nick], _id;
359 self:_route_stanza(stanza);
360 stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
364 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
366 elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
367 origin.send(st.error_reply(stanza, "modify", "bad-request"));
368 elseif current_nick and stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
369 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
370 self:handle_to_occupant(origin, st.presence({type='unavailable', from=stanza.attr.from, to=stanza.attr.to})
371 :tag('status'):text('Kicked: '..get_error_condition(stanza))); -- send unavailable
372 else -- private stanza
373 local o_data = self._occupants[to];
375 log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
376 local jid = o_data.jid;
377 local bare = jid_bare(jid);
378 stanza.attr.to, stanza.attr.from = jid, current_nick;
379 local id = stanza.attr.id;
380 if stanza.name=='iq' and type=='get' and stanza.tags[1].attr.xmlns == 'vcard-temp' and bare ~= jid then
381 stanza.attr.to = bare;
382 stanza.attr.id = base64.encode(jid.."\0"..id.."\0"..md5(from));
384 self:_route_stanza(stanza);
385 stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
386 elseif type ~= "error" and type ~= "result" then -- recipient not in room
387 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
392 function room_mt:send_form(origin, stanza)
393 local title = "Configuration for "..self.jid;
394 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
395 :tag("x", {xmlns='jabber:x:data', type='form'})
396 :tag("title"):text(title):up()
397 :tag("instructions"):text(title):up()
398 :tag("field", {type='hidden', var='FORM_TYPE'}):tag("value"):text("http://jabber.org/protocol/muc#roomconfig"):up():up()
399 :tag("field", {type='boolean', label='Make Room Persistent?', var='muc#roomconfig_persistentroom'})
400 :tag("value"):text(self._data.persistent and "1" or "0"):up()
402 :tag("field", {type='boolean', label='Make Room Publicly Searchable?', var='muc#roomconfig_publicroom'})
403 :tag("value"):text(self._data.hidden and "0" or "1"):up()
408 function room_mt:process_form(origin, stanza)
409 local query = stanza.tags[1];
411 for _, tag in ipairs(query.tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end
412 if not form then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return; end
413 if form.attr.type == "cancel" then origin.send(st.reply(stanza)); return; end
414 if form.attr.type ~= "submit" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
416 for _, field in pairs(form.tags) do
417 if field.name == "field" and field.attr.var and field.tags[1].name == "value" and #field.tags[1].tags == 0 then
418 fields[field.attr.var] = field.tags[1][1] or "";
421 if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
423 local persistent = fields['muc#roomconfig_persistentroom'];
424 if persistent == "0" or persistent == "false" then persistent = nil; elseif persistent == "1" or persistent == "true" then persistent = true;
425 else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
426 self._data.persistent = persistent;
427 module:log("debug", "persistent=%s", tostring(persistent));
429 local public = fields['muc#roomconfig_publicroom'];
430 if public == "0" or public == "false" then public = nil; elseif public == "1" or public == "true" then public = true;
431 else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
432 self._data.hidden = not public and true or nil;
434 if self.save then self:save(true); end
435 origin.send(st.reply(stanza));
438 function room_mt:destroy(newjid, reason, password)
439 local pr = st.presence({type = "unavailable"})
440 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
441 :tag("item", { affiliation='none', role='none' }):up()
442 :tag("destroy", {jid=newjid})
443 if reason then pr:tag("reason"):text(reason):up(); end
444 if password then pr:tag("password"):text(password):up(); end
445 for nick, occupant in pairs(self._occupants) do
447 for jid in pairs(occupant.sessions) do
449 self:_route_stanza(pr);
450 self._jid_nick[jid] = nil;
452 self._occupants[nick] = nil;
454 self._data.persistent = nil;
455 if self.save then self:save(true); end
458 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
459 local type = stanza.attr.type;
460 local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
461 if stanza.name == "iq" then
462 if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" then
463 origin.send(room_get_disco_info(self, stanza));
464 elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" then
465 origin.send(room_get_disco_items(self, stanza));
466 elseif xmlns == "http://jabber.org/protocol/muc#admin" then
467 local actor = stanza.attr.from;
468 local affiliation = self:get_affiliation(actor);
469 local current_nick = self._jid_nick[actor];
470 local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation);
471 local item = stanza.tags[1].tags[1];
472 if item and item.name == "item" then
473 if type == "set" then
474 local callback = function() origin.send(st.reply(stanza)); end
475 if item.attr.jid then -- Validate provided JID
476 item.attr.jid = jid_prep(item.attr.jid);
477 if not item.attr.jid then
478 origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
482 if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
483 local occupant = self._occupants[self.jid.."/"..item.attr.nick];
484 if occupant then item.attr.jid = occupant.jid; end
486 local reason = item.tags[1] and item.tags[1].name == "reason" and #item.tags[1] == 1 and item.tags[1][1];
487 if item.attr.affiliation and item.attr.jid and not item.attr.role then
488 local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback, reason);
489 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
490 elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
491 local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback, reason);
492 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
494 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
496 elseif type == "get" then
497 local _aff = item.attr.affiliation;
498 local _rol = item.attr.role;
499 if _aff and not _rol then
500 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
501 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
502 for jid, affiliation in pairs(self._affiliations) do
503 if affiliation == _aff then
504 reply:tag("item", {affiliation = _aff, jid = jid}):up();
509 origin.send(st.error_reply(stanza, "auth", "forbidden"));
511 elseif _rol and not _aff then
512 if role == "moderator" then
513 -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway?
514 if _rol == "none" then _rol = nil; end
515 local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
516 for nick, occupant in pairs(self._occupants) do
517 if occupant.role == _rol then
518 reply:tag("item", {nick = nick, role = _rol or "none", affiliation = occupant.affiliation or "none", jid = occupant.jid}):up();
523 origin.send(st.error_reply(stanza, "auth", "forbidden"));
526 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
529 elseif type == "set" or type == "get" then
530 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
532 elseif xmlns == "http://jabber.org/protocol/muc#owner" and (type == "get" or type == "set") and stanza.tags[1].name == "query" then
533 if self:get_affiliation(stanza.attr.from) ~= "owner" then
534 origin.send(st.error_reply(stanza, "auth", "forbidden"));
535 elseif stanza.attr.type == "get" then
536 self:send_form(origin, stanza);
537 elseif stanza.attr.type == "set" then
538 local child = stanza.tags[1].tags[1];
540 origin.send(st.error_reply(stanza, "auth", "bad-request"));
541 elseif child.name == "destroy" then
542 local newjid = child.attr.jid;
543 local reason, password;
544 for _,tag in ipairs(child.tags) do
545 if tag.name == "reason" then
546 reason = #tag.tags == 0 and tag[1];
547 elseif tag.name == "password" then
548 password = #tag.tags == 0 and tag[1];
551 self:destroy(newjid, reason, password);
552 origin.send(st.reply(stanza));
554 self:process_form(origin, stanza);
557 elseif type == "set" or type == "get" then
558 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
560 elseif stanza.name == "message" and type == "groupchat" then
561 local from, to = stanza.attr.from, stanza.attr.to;
562 local room = jid_bare(to);
563 local current_nick = self._jid_nick[from];
564 local occupant = self._occupants[current_nick];
565 if not occupant then -- not in room
566 origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
567 elseif occupant.role == "visitor" then
568 origin.send(st.error_reply(stanza, "cancel", "forbidden"));
570 local from = stanza.attr.from;
571 stanza.attr.from = current_nick;
572 local subject = getText(stanza, {"subject"});
574 if occupant.role == "moderator" then
575 self:set_subject(current_nick, subject); -- TODO use broadcast_message_stanza
577 stanza.attr.from = from;
578 origin.send(st.error_reply(stanza, "cancel", "forbidden"));
581 self:broadcast_message(stanza, true);
583 stanza.attr.from = from;
585 elseif stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
586 local current_nick = self._jid_nick[stanza.attr.from];
587 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
588 self:handle_to_occupant(origin, st.presence({type='unavailable', from=stanza.attr.from, to=stanza.attr.to})
589 :tag('status'):text('Kicked: '..get_error_condition(stanza))); -- send unavailable
590 elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
591 local to = stanza.attr.to;
592 local current_nick = self._jid_nick[stanza.attr.from];
594 stanza.attr.to = current_nick;
595 self:handle_to_occupant(origin, stanza);
597 elseif type ~= "error" and type ~= "result" then
598 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
600 elseif stanza.name == "message" and not stanza.attr.type and #stanza.tags == 1 and self._jid_nick[stanza.attr.from]
601 and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" then
602 local x = stanza.tags[1];
603 local payload = (#x.tags == 1 and x.tags[1]);
604 if payload and payload.name == "invite" and payload.attr.to then
605 local _from, _to = stanza.attr.from, stanza.attr.to;
606 local _invitee = jid_prep(payload.attr.to);
608 local _reason = payload.tags[1] and payload.tags[1].name == 'reason' and #payload.tags[1].tags == 0 and payload.tags[1][1];
609 local invite = st.message({from = _to, to = _invitee, id = stanza.attr.id})
610 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
611 :tag('invite', {from=_from})
612 :tag('reason'):text(_reason or ""):up()
615 :tag('x', {xmlns="jabber:x:conference", jid=_to}) -- COMPAT: Some older clients expect this
618 :tag('body') -- Add a plain message for clients which don't support invites
619 :text(_from..' invited you to the room '.._to..(_reason and (' ('.._reason..')') or ""))
621 self:_route_stanza(invite);
623 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
626 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
629 if type == "error" or type == "result" then return; end
630 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
634 function room_mt:handle_stanza(origin, stanza)
635 local to_node, to_host, to_resource = jid_split(stanza.attr.to);
637 self:handle_to_occupant(origin, stanza);
639 self:handle_to_room(origin, stanza);
643 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
645 function room_mt:get_affiliation(jid)
646 local node, host, resource = jid_split(jid);
647 local bare = node and node.."@"..host or host;
648 local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
649 if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
652 function room_mt:set_affiliation(actor, jid, affiliation, callback, reason)
654 if affiliation == "none" then affiliation = nil; end
655 if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
656 return nil, "modify", "not-acceptable";
658 if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
659 if jid_bare(actor) == jid then return nil, "cancel", "not-allowed"; end
660 self._affiliations[jid] = affiliation;
661 local role = self:get_default_role(affiliation);
662 local p = st.presence()
663 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
664 :tag("item", {affiliation=affiliation or "none", role=role or "none"})
665 :tag("reason"):text(reason or ""):up()
668 local item = x.tags[1];
669 if not role then -- getting kicked
670 p.attr.type = "unavailable";
671 if affiliation == "outcast" then
672 x:tag("status", {code="301"}):up(); -- banned
674 x:tag("status", {code="321"}):up(); -- affiliation change
677 local modified_nicks = {};
678 for nick, occupant in pairs(self._occupants) do
679 if jid_bare(occupant.jid) == jid then
680 if not role then -- getting kicked
681 self._occupants[nick] = nil;
683 t_insert(modified_nicks, nick);
684 occupant.affiliation, occupant.role = affiliation, role;
687 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
688 if not role then self._jid_nick[jid] = nil; end
690 self:_route_stanza(p);
694 if self.save then self:save(); end
695 if callback then callback(); end
696 for _, nick in ipairs(modified_nicks) do
698 self:broadcast_except_nick(p, nick);
703 function room_mt:get_role(nick)
704 local session = self._occupants[nick];
705 return session and session.role or nil;
707 function room_mt:set_role(actor, nick, role, callback, reason)
708 if role == "none" then role = nil; end
709 if role and role ~= "moderator" and role ~= "participant" and role ~= "visitor" then return nil, "modify", "not-acceptable"; end
710 if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
711 local occupant = self._occupants[nick];
712 if not occupant then return nil, "modify", "not-acceptable"; end
713 if occupant.affiliation == "owner" or occupant.affiliation == "admin" then return nil, "cancel", "not-allowed"; end
714 local p = st.presence({from = nick})
715 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
716 :tag("item", {affiliation=occupant.affiliation or "none", nick=nick, role=role or "none"})
717 :tag("reason"):text(reason or ""):up()
719 if not role then -- kick
720 p.attr.type = "unavailable";
721 self._occupants[nick] = nil;
722 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
723 self._jid_nick[jid] = nil;
725 p:tag("status", {code = "307"}):up();
727 occupant.role = role;
729 for jid in pairs(occupant.sessions) do -- send to all sessions of the nick
731 self:_route_stanza(p);
733 if callback then callback(); end
734 self:broadcast_except_nick(p, nick);
738 function room_mt:_route_stanza(stanza)
740 local to_occupant = self._occupants[self._jid_nick[stanza.attr.to]];
741 local from_occupant = self._occupants[stanza.attr.from];
742 if stanza.name == "presence" then
743 if to_occupant and from_occupant then
744 if to_occupant.role == "moderator" or jid_bare(to_occupant.jid) == jid_bare(from_occupant.jid) then
745 for i=#stanza.tags,1,-1 do
746 local tag = stanza.tags[i];
747 if tag.name == "x" and tag.attr.xmlns == "http://jabber.org/protocol/muc#user" then
756 for _, item in pairs(muc_child.tags) do
757 if item.name == "item" then
758 if from_occupant == to_occupant then
759 item.attr.jid = stanza.attr.to;
761 item.attr.jid = from_occupant.jid;
766 self:route_stanza(stanza);
768 for _, item in pairs(muc_child.tags) do
769 if item.name == "item" then
776 local _M = {}; -- module "muc"
778 function _M.new_room(jid)
779 return setmetatable({