MUC: Prep given JID when changing affiliation.
[prosody.git] / plugins / muc / muc.lib.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2009 Matthew Wild
3 -- Copyright (C) 2008-2009 Waqas Hussain
4 -- 
5 -- This project is MIT/X11 licensed. Please see the
6 -- COPYING file in the source package for more information.
7 --
8
9 local datamanager = require "util.datamanager";
10 local datetime = require "util.datetime";
11
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;
22
23 local muc_domain = nil; --module:get_host();
24 local history_length = 20;
25
26 ------------
27 local function filter_xmlns_from_array(array, filters)
28         local count = 0;
29         for i=#array,1,-1 do
30                 local attr = array[i].attr;
31                 if filters[attr and attr.xmlns] then
32                         t_remove(array, i);
33                         count = count + 1;
34                 end
35         end
36         return count;
37 end
38 local function filter_xmlns_from_stanza(stanza, filters)
39         if filters then
40                 if filter_xmlns_from_array(stanza.tags, filters) ~= 0 then
41                         return stanza, filter_xmlns_from_array(stanza, filters);
42                 end
43         end
44         return stanza, 0;
45 end
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), presence_filters);
49 end
50 local kickable_error_conditions = {
51         ["gone"] = true;
52         ["internal-server-error"] = true;
53         ["item-not-found"] = true;
54         ["jid-malformed"] = true;
55         ["recipient-unavailable"] = true;
56         ["redirect"] = true;
57         ["remote-server-not-found"] = true;
58         ["remote-server-timeout"] = true;
59         ["service-unavailable"] = true;
60 };
61 local function get_kickable_error(stanza)
62         for _, tag in ipairs(stanza.tags) do
63                 if tag.name == "error" and tag.attr.xmlns == "jabber:client" then
64                         for _, cond in ipairs(tag.tags) do
65                                 if cond.attr.xmlns == "urn:ietf:params:xml:ns:xmpp-stanzas" then
66                                         return kickable_error_conditions[cond.name] and cond.name;
67                                 end
68                         end
69                         return true; -- malformed error message
70                 end
71         end
72         return true; -- malformed error message
73 end
74 local function getUsingPath(stanza, path, getText)
75         local tag = stanza;
76         for _, name in ipairs(path) do
77                 if type(tag) ~= 'table' then return; end
78                 tag = tag:child_with_name(name);
79         end
80         if tag and getText then tag = table.concat(tag); end
81         return tag;
82 end
83 local function getTag(stanza, path) return getUsingPath(stanza, path); end
84 local function getText(stanza, path) return getUsingPath(stanza, path, true); end
85 -----------
86
87 --[[function get_room_disco_info(room, stanza)
88         return st.iq({type='result', id=stanza.attr.id, from=stanza.attr.to, to=stanza.attr.from}):query("http://jabber.org/protocol/disco#info")
89                 :tag("identity", {category='conference', type='text', name=room._data["name"]):up()
90                 :tag("feature", {var="http://jabber.org/protocol/muc"}); -- TODO cache disco reply
91 end
92 function get_room_disco_items(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#items");
94 end -- TODO allow non-private rooms]]
95
96 --
97
98 local room_mt = {};
99 room_mt.__index = room_mt;
100
101 function room_mt:get_default_role(affiliation)
102         if affiliation == "owner" or affiliation == "admin" then
103                 return "moderator";
104         elseif affiliation == "member" or not affiliation then
105                 return "participant";
106         end
107 end
108
109 function room_mt:broadcast_presence(stanza, code, nick)
110         stanza = get_filtered_presence(stanza);
111         local occupant = self._occupants[stanza.attr.from];
112         stanza:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
113                 :tag("item", {affiliation=occupant.affiliation, role=occupant.role, nick=nick}):up();
114         if code then
115                 stanza:tag("status", {code=code}):up();
116         end
117         self:broadcast_except_nick(stanza, stanza.attr.from);
118         local me = self._occupants[stanza.attr.from];
119         if me then
120                 stanza:tag("status", {code='110'});
121                 for jid in pairs(me.sessions) do
122                         stanza.attr.to = jid;
123                         self:route_stanza(stanza);
124                 end
125         end
126 end
127 function room_mt:broadcast_message(stanza, historic)
128         for occupant, o_data in pairs(self._occupants) do
129                 for jid in pairs(o_data.sessions) do
130                         stanza.attr.to = jid;
131                         self:route_stanza(stanza);
132                 end
133         end
134         if historic then -- add to history
135                 local history = self._data['history'];
136                 if not history then history = {}; self._data['history'] = history; end
137                 -- stanza = st.clone(stanza);
138                 stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = muc_domain, stamp = datetime.datetime()}):up(); -- XEP-0203
139                 stanza:tag("x", {xmlns = "jabber:x:delay", from = muc_domain, stamp = datetime.legacy()}):up(); -- XEP-0091 (deprecated)
140                 t_insert(history, st.clone(st.preserialize(stanza)));
141                 while #history > history_length do t_remove(history, 1) end
142         end
143 end
144 function room_mt:broadcast_except_nick(stanza, nick)
145         for rnick, occupant in pairs(self._occupants) do
146                 if rnick ~= nick then
147                         for jid in pairs(occupant.sessions) do
148                                 stanza.attr.to = jid;
149                                 self:route_stanza(stanza);
150                         end
151                 end
152         end
153 end
154
155 function room_mt:send_occupant_list(to)
156         local current_nick = self._jid_nick[to];
157         for occupant, o_data in pairs(self._occupants) do
158                 if occupant ~= current_nick then
159                         local pres = get_filtered_presence(o_data.sessions[o_data.jid]);
160                         pres.attr.to, pres.attr.from = to, occupant;
161                         pres:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
162                                 :tag("item", {affiliation=o_data.affiliation, role=o_data.role}):up();
163                         self:route_stanza(pres);
164                 end
165         end
166 end
167 function room_mt:send_history(to)
168         local history = self._data['history']; -- send discussion history
169         if history then
170                 for _, msg in ipairs(history) do
171                         msg = st.deserialize(msg);
172                         msg.attr.to=to;
173                         self:route_stanza(msg);
174                 end
175         end
176         if self._data['subject'] then
177                 self:route_stanza(st.message({type='groupchat', from=self.jid, to=to}):tag("subject"):text(self._data['subject']));
178         end
179 end
180
181 local function room_get_disco_info(self, stanza)
182         return st.reply(stanza):query("http://jabber.org/protocol/disco#info")
183                 :tag("identity", {category="conference", type="text"}):up()
184                 :tag("feature", {var="http://jabber.org/protocol/muc"});
185 end
186 local function room_get_disco_items(self, stanza)
187         return st.reply(stanza):query("http://jabber.org/protocol/disco#items");
188 end
189 function room_mt:set_subject(current_nick, subject)
190         -- TODO check nick's authority
191         if subject == "" then subject = nil; end
192         self._data['subject'] = subject;
193         if self.save then self:save(); end
194         local msg = st.message({type='groupchat', from=current_nick})
195                 :tag('subject'):text(subject):up();
196         self:broadcast_message(msg, false);
197         return true;
198 end
199
200 function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
201         local from, to = stanza.attr.from, stanza.attr.to;
202         local room = jid_bare(to);
203         local current_nick = self._jid_nick[from];
204         local type = stanza.attr.type;
205         log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
206         if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
207         if stanza.name == "presence" then
208                 local pr = get_filtered_presence(stanza);
209                 pr.attr.from = current_nick;
210                 if type == "error" then -- error, kick em out!
211                         if current_nick then
212                                 log("debug", "kicking %s from %s", current_nick, room);
213                                 self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
214                                         :tag('status'):text('This participant is kicked from the room because he sent an error presence')); -- send unavailable
215                         end
216                 elseif type == "unavailable" then -- unavailable
217                         if current_nick then
218                                 log("debug", "%s leaving %s", current_nick, room);
219                                 local occupant = self._occupants[current_nick];
220                                 local old_session = occupant.sessions[from];
221                                 local new_jid = next(occupant.sessions);
222                                 if new_jid == from then new_jid = next(occupant.sessions, new_jid); end
223                                 if new_jid then
224                                         occupant.jid = new_jid;
225                                         occupant.sessions[from] = nil;
226                                         local pr = st.clone(occupant[new_jid])
227                                                 :tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
228                                                 :tag("item", {affiliation=occupant.affiliation, role=occupant.role});
229                                         self:broadcast_except_nick(pr, current_nick);
230                                 else
231                                         occupant.role = 'none';
232                                         self:broadcast_presence(pr);
233                                         self._occupants[current_nick] = nil;
234                                 end
235                                 self._jid_nick[from] = nil;
236                         end
237                 elseif not type then -- available
238                         if current_nick then
239                                 --if #pr == #stanza or current_nick ~= to then -- commented because google keeps resending directed presence
240                                         if current_nick == to then -- simple presence
241                                                 log("debug", "%s broadcasted presence", current_nick);
242                                                 self._occupants[current_nick].sessions[from] = pr;
243                                                 self:broadcast_presence(pr);
244                                         else -- change nick
245                                                 if self._occupants[to] then
246                                                         log("debug", "%s couldn't change nick", current_nick);
247                                                         local reply = st.error_reply(stanza, "cancel", "conflict"):up();
248                                                         reply.tags[1].attr.code = "409";
249                                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
250                                                 else
251                                                         local data = self._occupants[current_nick];
252                                                         local to_nick = select(3, jid_split(to));
253                                                         if to_nick then
254                                                                 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
255                                                                 local p = st.presence({type='unavailable', from=current_nick});
256                                                                 self:broadcast_presence(p, '303', to_nick);
257                                                                 self._occupants[current_nick] = nil;
258                                                                 self._occupants[to] = data;
259                                                                 self._jid_nick[from] = to;
260                                                                 pr.attr.from = to;
261                                                                 self._occupants[to].sessions[from] = pr;
262                                                                 self:broadcast_presence(pr);
263                                                         else
264                                                                 --TODO malformed-jid
265                                                         end
266                                                 end
267                                         end
268                                 --else -- possible rejoin
269                                 --      log("debug", "%s had connection replaced", current_nick);
270                                 --      self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
271                                 --              :tag('status'):text('Replaced by new connection'):up()); -- send unavailable
272                                 --      self:handle_to_occupant(origin, stanza); -- resend available
273                                 --end
274                         else -- enter room
275                                 local new_nick = to;
276                                 if self._occupants[to] then
277                                         new_nick = nil;
278                                 end
279                                 if not new_nick then
280                                         log("debug", "%s couldn't join due to nick conflict: %s", from, to);
281                                         local reply = st.error_reply(stanza, "cancel", "conflict"):up();
282                                         reply.tags[1].attr.code = "409";
283                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
284                                 else
285                                         log("debug", "%s joining as %s", from, to);
286                                         if not next(self._affiliations) then -- new room, no owners
287                                                 self._affiliations[jid_bare(from)] = "owner";
288                                         end
289                                         local affiliation = self:get_affiliation(from);
290                                         local role = self:get_default_role(affiliation)
291                                         if role then -- new occupant
292                                                 self._occupants[to] = {affiliation=affiliation, role=role, jid=from, sessions={[from]=get_filtered_presence(stanza)}};
293                                                 self._jid_nick[from] = to;
294                                                 self:send_occupant_list(from);
295                                                 pr.attr.from = to;
296                                                 self:broadcast_presence(pr);
297                                                 self:send_history(from);
298                                         else -- banned
299                                                 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
300                                                 reply.tags[1].attr.code = "403";
301                                                 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
302                                         end
303                                 end
304                         end
305                 elseif type ~= 'result' then -- bad type
306                         origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
307                 end
308         elseif not current_nick then -- not in room
309                 if type == "error" or type == "result" then
310                         local id = stanza.name == "iq" and stanza.attr.id and base64.decode(stanza.attr.id);
311                         local _nick, _id, _hash = (id or ""):match("^(.+)%z(.*)%z(.+)$");
312                         local occupant = self._occupants[stanza.attr.to];
313                         if occupant and _nick and self._jid_nick[_nick] and _id and _hash then
314                                 local id, _to = stanza.attr.id;
315                                 for jid in pairs(occupant.sessions) do
316                                         if md5(jid) == _hash then
317                                                 _to = jid;
318                                                 break;
319                                         end
320                                 end
321                                 if _to then
322                                         stanza.attr.to, stanza.attr.from, stanza.attr.id = _to, self._jid_nick[_nick], _id;
323                                         self:route_stanza(stanza);
324                                         stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
325                                 end
326                         end
327                 else
328                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
329                 end
330         elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
331                 origin.send(st.error_reply(stanza, "modify", "bad-request"));
332         else -- private stanza
333                 local o_data = self._occupants[to];
334                 if o_data then
335                         log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
336                         local jid = o_data.jid;
337                         local bare = jid_bare(jid);
338                         stanza.attr.to, stanza.attr.from = jid, current_nick;
339                         local id = stanza.attr.id;
340                         if stanza.name=='iq' and type=='get' and stanza.tags[1].attr.xmlns == 'vcard-temp' and bare ~= jid then
341                                 stanza.attr.to = bare;
342                                 stanza.attr.id = base64.encode(jid.."\0"..id.."\0"..md5(from));
343                         end
344                         self:route_stanza(stanza);
345                         stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
346                 elseif type ~= "error" and type ~= "result" then -- recipient not in room
347                         origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
348                 end
349         end
350 end
351
352 function room_mt:handle_form(origin, stanza)
353         if self:get_affiliation(stanza.attr.from) ~= "owner" then origin.send(st.error_reply(stanza, "auth", "forbidden")); return; end
354         if stanza.attr.type == "get" then
355                 local title = "Configuration for "..self.jid;
356                 origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
357                         :tag("x", {xmlns='jabber:x:data', type='form'})
358                                 :tag("title"):text(title):up()
359                                 :tag("instructions"):text(title):up()
360                                 :tag("field", {type='hidden', var='FORM_TYPE'}):tag("value"):text("http://jabber.org/protocol/muc#roomconfig"):up():up()
361                                 :tag("field", {type='boolean', label='Make Room Persistent?', var='muc#roomconfig_persistentroom'})
362                                         :tag("value"):text(self._data.persistent and "1" or "0"):up()
363                                 :up()
364                                 :tag("field", {type='boolean', label='Make Room Publicly Searchable?', var='muc#roomconfig_publicroom'})
365                                         :tag("value"):text(self._data.hidden and "0" or "1"):up()
366                                 :up()
367                 );
368         elseif stanza.attr.type == "set" then
369                 local query = stanza.tags[1];
370                 local form;
371                 for _, tag in ipairs(query.tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end
372                 if not form then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return; end
373                 if form.attr.type == "cancel" then origin.send(st.reply(stanza)); return; end
374                 if form.attr.type ~= "submit" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
375                 local fields = {};
376                 for _, field in pairs(form.tags) do
377                         if field.name == "field" and field.attr.var and field.tags[1].name == "value" and #field.tags[1].tags == 0 then
378                                 fields[field.attr.var] = field.tags[1][1] or "";
379                         end
380                 end
381                 if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
382
383                 local persistent = fields['muc#roomconfig_persistentroom'];
384                 if persistent == "0" or persistent == "false" then persistent = nil; elseif persistent == "1" or persistent == "true" then persistent = true;
385                 else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
386                 self._data.persistent = persistent;
387                 module:log("debug", "persistent=%s", tostring(persistent));
388
389                 local public = fields['muc#roomconfig_publicroom'];
390                 if public == "0" or public == "false" then public = nil; elseif public == "1" or public == "true" then public = true;
391                 else origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
392                 self._data.hidden = not public and true or nil;
393
394                 if self.save then self:save(true); end
395                 origin.send(st.reply(stanza));
396         end
397 end
398
399 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
400         local type = stanza.attr.type;
401         local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
402         if stanza.name == "iq" then
403                 if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" then
404                         origin.send(room_get_disco_info(self, stanza));
405                 elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" then
406                         origin.send(room_get_disco_items(self, stanza));
407                 elseif xmlns == "http://jabber.org/protocol/muc#admin" then
408                         local actor = stanza.attr.from;
409                         local affiliation = self:get_affiliation(actor);
410                         local current_nick = self._jid_nick[actor];
411                         local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation);
412                         local item = stanza.tags[1].tags[1];
413                         if item and item.name == "item" then
414                                 if type == "set" then
415                                         local callback = function() origin.send(st.reply(stanza)); end
416                                         if item.attr.jid then -- Validate provided JID
417                                                 item.attr.jid = jid_prep(item.attr.jid);
418                                                 if not item.attr.jid then
419                                                         origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
420                                                         return;
421                                                 end
422                                         end
423                                         if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
424                                                 local occupant = self._occupants[self.jid.."/"..item.attr.nick];
425                                                 if occupant then item.attr.jid = occupant.jid; end
426                                         end
427                                         if item.attr.affiliation and item.attr.jid and not item.attr.role then
428                                                 local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback);
429                                                 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
430                                         elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
431                                                 local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback);
432                                                 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
433                                         else
434                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
435                                         end
436                                 elseif type == "get" then
437                                         local _aff = item.attr.affiliation;
438                                         local _rol = item.attr.role;
439                                         if _aff and not _rol then
440                                                 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
441                                                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
442                                                         for jid, affiliation in pairs(self._affiliations) do
443                                                                 if affiliation == _aff then
444                                                                         reply:tag("item", {affiliation = _aff, jid = jid}):up();
445                                                                 end
446                                                         end
447                                                         origin.send(reply);
448                                                 else
449                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
450                                                 end
451                                         elseif _rol and not _aff then
452                                                 if role == "moderator" then
453                                                         -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway?
454                                                         if _rol == "none" then _rol = nil; end
455                                                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
456                                                         for nick, occupant in pairs(self._occupants) do
457                                                                 if occupant.role == _rol then
458                                                                         reply:tag("item", {nick = nick, role = _rol or "none", affiliation = occupant.affiliation or "none", jid = occupant.jid}):up();
459                                                                 end
460                                                         end
461                                                         origin.send(reply);
462                                                 else
463                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
464                                                 end
465                                         else
466                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
467                                         end
468                                 end
469                         elseif type == "set" or type == "get" then
470                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
471                         end
472                 elseif xmlns == "http://jabber.org/protocol/muc#owner" and (type == "get" or type == "set") and stanza.tags[1].name == "query" then
473                         self:handle_form(origin, stanza);
474                 elseif type == "set" or type == "get" then
475                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
476                 end
477         elseif stanza.name == "message" and type == "groupchat" then
478                 local from, to = stanza.attr.from, stanza.attr.to;
479                 local room = jid_bare(to);
480                 local current_nick = self._jid_nick[from];
481                 if not current_nick then -- not in room
482                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
483                 else
484                         local from = stanza.attr.from;
485                         stanza.attr.from = current_nick;
486                         local subject = getText(stanza, {"subject"});
487                         if subject then
488                                 self:set_subject(current_nick, subject); -- TODO use broadcast_message_stanza
489                         else
490                                 self:broadcast_message(stanza, true);
491                         end
492                 end
493         elseif stanza.name == "message" and type == "error" and get_kickable_error(stanza) then
494                 local current_nick = self._jid_nick[stanza.attr.from];
495                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
496                 self:handle_to_occupant(origin, st.presence({type='unavailable', from=stanza.attr.from, to=stanza.attr.to})
497                         :tag('status'):text('This participant is kicked from the room because he sent an error message to another occupant')); -- send unavailable
498         elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
499                 local to = stanza.attr.to;
500                 local current_nick = self._jid_nick[stanza.attr.from];
501                 if current_nick then
502                         stanza.attr.to = current_nick;
503                         self:handle_to_occupant(origin, stanza);
504                         stanza.attr.to = to;
505                 elseif type ~= "error" and type ~= "result" then
506                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
507                 end
508         elseif stanza.name == "message" and not stanza.attr.type and #stanza.tags == 1 and self._jid_nick[stanza.attr.from]
509                 and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" and #stanza.tags[1].tags == 1
510                 and stanza.tags[1].tags[1].name == "invite" and stanza.tags[1].tags[1].attr.to then
511                 local _from, _to = stanza.attr.from, stanza.attr.to;
512                 local _invitee = stanza.tags[1].tags[1].attr.to;
513                 stanza.attr.from, stanza.attr.to = _to, _invitee;
514                 stanza.tags[1].tags[1].attr.from, stanza.tags[1].tags[1].attr.to = _from, nil;
515                 self:route_stanza(stanza);
516                 stanza.tags[1].tags[1].attr.from, stanza.tags[1].tags[1].attr.to = nil, _invitee;
517                 stanza.attr.from, stanza.attr.to = _from, _to;
518         else
519                 if type == "error" or type == "result" then return; end
520                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
521         end
522 end
523
524 function room_mt:handle_stanza(origin, stanza)
525         local to_node, to_host, to_resource = jid_split(stanza.attr.to);
526         if to_resource then
527                 self:handle_to_occupant(origin, stanza);
528         else
529                 self:handle_to_room(origin, stanza);
530         end
531 end
532
533 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
534
535 function room_mt:get_affiliation(jid)
536         local node, host, resource = jid_split(jid);
537         local bare = node and node.."@"..host or host;
538         local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
539         if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
540         return result;
541 end
542 function room_mt:set_affiliation(actor, jid, affiliation, callback)
543         jid = jid_bare(jid);
544         if affiliation == "none" then affiliation = nil; end
545         if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
546                 return nil, "modify", "not-acceptable";
547         end
548         if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
549         if jid_bare(actor) == jid then return nil, "cancel", "not-allowed"; end
550         self._affiliations[jid] = affiliation;
551         local role = self:get_default_role(affiliation);
552         local p = st.presence()
553                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
554                         :tag("item", {affiliation=affiliation or "none", role=role or "none"}):up();
555         local x = p.tags[1];
556         local item = x.tags[1];
557         if not role then -- getting kicked
558                 p.attr.type = "unavailable";
559                 if affiliation == "outcast" then
560                         x:tag("status", {code="301"}):up(); -- banned
561                 else
562                         x:tag("status", {code="321"}):up(); -- affiliation change
563                 end
564         end
565         local modified_nicks = {};
566         for nick, occupant in pairs(self._occupants) do
567                 if jid_bare(occupant.jid) == jid then
568                         if not role then -- getting kicked
569                                 self._occupants[nick] = nil;
570                         else
571                                 t_insert(modified_nicks, nick);
572                                 occupant.affiliation, occupant.role = affiliation, role;
573                         end
574                         p.attr.from = nick;
575                         for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
576                                 if not role then self._jid_nick[jid] = nil; end
577                                 p.attr.to = jid;
578                                 self:route_stanza(p);
579                         end
580                 end
581         end
582         if self.save then self:save(); end
583         if callback then callback(); end
584         for _, nick in ipairs(modified_nicks) do
585                 p.attr.from = nick;
586                 self:broadcast_except_nick(p, nick);
587         end
588         return true;
589 end
590
591 function room_mt:get_role(nick)
592         local session = self._occupants[nick];
593         return session and session.role or nil;
594 end
595 function room_mt:set_role(actor, nick, role, callback)
596         if role == "none" then role = nil; end
597         if role and role ~= "moderator" and role ~= "participant" and role ~= "visitor" then return nil, "modify", "not-acceptable"; end
598         if self:get_affiliation(actor) ~= "owner" then return nil, "cancel", "not-allowed"; end
599         local occupant = self._occupants[nick];
600         if not occupant then return nil, "modify", "not-acceptable"; end
601         if occupant.affiliation == "owner" or occupant.affiliation == "admin" then return nil, "cancel", "not-allowed"; end
602         local p = st.presence({from = nick})
603                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
604                         :tag("item", {affiliation=occupant.affiliation or "none", nick=nick, role=role or "none"}):up();
605         if not role then -- kick
606                 p.attr.type = "unavailable";
607                 self._occupants[nick] = nil;
608                 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
609                         self._jid_nick[jid] = nil;
610                 end
611                 p:tag("status", {code = "307"}):up();
612         else
613                 occupant.role = role;
614         end
615         for jid in pairs(occupant.sessions) do -- send to all sessions of the nick
616                 p.attr.to = jid;
617                 self:route_stanza(p);
618         end
619         if callback then callback(); end
620         self:broadcast_except_nick(p, nick);
621         return true;
622 end
623
624 local _M = {}; -- module "muc"
625
626 function _M.new_room(jid)
627         return setmetatable({
628                 jid = jid;
629                 _jid_nick = {};
630                 _occupants = {};
631                 _data = {};
632                 _affiliations = {};
633         }, room_mt);
634 end
635
636 return _M;