MUC: Added support for the room-destroy owner use case.
[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):reset(), 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         ["malformed error"] = true;
61 };
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
67                                         return cond.name;
68                                 end
69                         end
70                         return "malformed error";
71                 end
72         end
73         return "malformed error";
74 end
75 local function is_kickable_error(stanza)
76         local cond = get_error_condition(stanza);
77         return kickable_error_conditions[cond] and cond;
78 end
79 local function getUsingPath(stanza, path, getText)
80         local tag = stanza;
81         for _, name in ipairs(path) do
82                 if type(tag) ~= 'table' then return; end
83                 tag = tag:child_with_name(name);
84         end
85         if tag and getText then tag = table.concat(tag); end
86         return tag;
87 end
88 local function getTag(stanza, path) return getUsingPath(stanza, path); end
89 local function getText(stanza, path) return getUsingPath(stanza, path, true); end
90 -----------
91
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
96 end
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]]
100
101 --
102
103 local room_mt = {};
104 room_mt.__index = room_mt;
105
106 function room_mt:get_default_role(affiliation)
107         if affiliation == "owner" or affiliation == "admin" then
108                 return "moderator";
109         elseif affiliation == "member" or not affiliation then
110                 return "participant";
111         end
112 end
113
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();
119         if code then
120                 stanza:tag("status", {code=code}):up();
121         end
122         self:broadcast_except_nick(stanza, stanza.attr.from);
123         local me = self._occupants[stanza.attr.from];
124         if me then
125                 stanza:tag("status", {code='110'});
126                 stanza.attr.to = sid;
127                 self:_route_stanza(stanza);
128         end
129 end
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);
136                 end
137         end
138         stanza.attr.to = to;
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
147         end
148 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);
155                         end
156                 end
157         end
158 end
159
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);
169                 end
170         end
171 end
172 function room_mt:send_history(to)
173         local history = self._data['history']; -- send discussion history
174         if history then
175                 for _, msg in ipairs(history) do
176                         msg = st.deserialize(msg);
177                         msg.attr.to=to;
178                         self:_route_stanza(msg);
179                 end
180         end
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']));
183         end
184 end
185
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"});
190 end
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();
195         end
196         return reply;
197 end
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);
206         return true;
207 end
208
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!
220                         if current_nick then
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
224                         end
225                 elseif type == "unavailable" then -- unavailable
226                         if current_nick then
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
231                                 if new_jid then
232                                         local jid = occupant.jid;
233                                         occupant.jid = new_jid;
234                                         occupant.sessions[from] = nil;
235                                         pr.attr.to = from;
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);
246                                         end
247                                 else
248                                         occupant.role = 'none';
249                                         self:broadcast_presence(pr, from);
250                                         self._occupants[current_nick] = nil;
251                                 end
252                                 self._jid_nick[from] = nil;
253                         end
254                 elseif not type then -- available
255                         if current_nick then
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);
261                                         else -- change nick
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"}));
269                                                 else
270                                                         local data = self._occupants[current_nick];
271                                                         local to_nick = select(3, jid_split(to));
272                                                         if to_nick then
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;
279                                                                 pr.attr.from = to;
280                                                                 self._occupants[to].sessions[from] = pr;
281                                                                 self:broadcast_presence(pr, from);
282                                                         else
283                                                                 --TODO malformed-jid
284                                                         end
285                                                 end
286                                         end
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
292                                 --end
293                         else -- enter room
294                                 local new_nick = to;
295                                 local is_merge;
296                                 if self._occupants[to] then
297                                         if jid_bare(from) ~= jid_bare(self._occupants[to].jid) then
298                                                 new_nick = nil;
299                                         end
300                                         is_merge = true;
301                                 end
302                                 if not new_nick 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"}));
307                                 else
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";
311                                         end
312                                         local affiliation = self:get_affiliation(from);
313                                         local role = self:get_default_role(affiliation)
314                                         if role then -- new occupant
315                                                 if not is_merge then
316                                                         self._occupants[to] = {affiliation=affiliation, role=role, jid=from, sessions={[from]=get_filtered_presence(stanza)}};
317                                                 else
318                                                         self._occupants[to].sessions[from] = get_filtered_presence(stanza);
319                                                 end
320                                                 self._jid_nick[from] = to;
321                                                 self:send_occupant_list(from);
322                                                 pr.attr.from = to;
323                                                 if not is_merge then
324                                                         self:broadcast_presence(pr, from);
325                                                 else
326                                                         pr.attr.to = 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'}));
330                                                 end
331                                                 self:send_history(from);
332                                         else -- banned
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"}));
336                                         end
337                                 end
338                         end
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?
342                         end
343                 end
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
353                                                 _to = jid;
354                                                 break;
355                                         end
356                                 end
357                                 if _to 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;
361                                 end
362                         end
363                 else
364                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
365                 end
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];
374                 if o_data then
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));
383                         end
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"));
388                 end
389         end
390 end
391
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()
401                         :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()
404                         :up()
405         );
406 end
407
408 function room_mt:process_form(origin, stanza)
409         local query = stanza.tags[1];
410         local form;
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
415         local fields = {};
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 "";
419                 end
420         end
421         if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); return; end
422
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));
428
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;
433
434         if self.save then self:save(true); end
435         origin.send(st.reply(stanza));
436 end
437
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
446                 pr.attr.from = nick;
447                 for jid in pairs(occupant.sessions) do
448                         pr.attr.to = jid;
449                         self:_route_stanza(pr);
450                         self._jid_nick[jid] = nil;
451                 end
452                 self._occupants[nick] = nil;
453         end
454         self._data.persistent = nil;
455         if self.save then self:save(true); end
456 end
457
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"));
479                                                         return;
480                                                 end
481                                         end
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
485                                         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
493                                         else
494                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
495                                         end
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();
505                                                                 end
506                                                         end
507                                                         origin.send(reply);
508                                                 else
509                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
510                                                 end
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();
519                                                                 end
520                                                         end
521                                                         origin.send(reply);
522                                                 else
523                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
524                                                 end
525                                         else
526                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
527                                         end
528                                 end
529                         elseif type == "set" or type == "get" then
530                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
531                         end
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];
539                                 if not child then
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];
549                                                 end
550                                         end
551                                         self:destroy(newjid, reason, password);
552                                         origin.send(st.reply(stanza));
553                                 else
554                                         self:process_form(origin, stanza);
555                                 end
556                         end
557                 elseif type == "set" or type == "get" then
558                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
559                 end
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"));
569                 else
570                         local from = stanza.attr.from;
571                         stanza.attr.from = current_nick;
572                         local subject = getText(stanza, {"subject"});
573                         if subject then
574                                 if occupant.role == "moderator" then
575                                         self:set_subject(current_nick, subject); -- TODO use broadcast_message_stanza
576                                 else
577                                         stanza.attr.from = from;
578                                         origin.send(st.error_reply(stanza, "cancel", "forbidden"));
579                                 end
580                         else
581                                 self:broadcast_message(stanza, true);
582                         end
583                         stanza.attr.from = from;
584                 end
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];
593                 if current_nick then
594                         stanza.attr.to = current_nick;
595                         self:handle_to_occupant(origin, stanza);
596                         stanza.attr.to = to;
597                 elseif type ~= "error" and type ~= "result" then
598                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
599                 end
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);
607                         if _invitee then
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()
613                                                 :up()
614                                         :up()
615                                         :tag('x', {xmlns="jabber:x:conference", jid=_to}) -- COMPAT: Some older clients expect this
616                                                 :text(_reason or "")
617                                         :up()
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 ""))
620                                         :up();
621                                 self:_route_stanza(invite);
622                         else
623                                 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
624                         end
625                 else
626                         origin.send(st.error_reply(stanza, "cancel", "bad-request"));
627                 end
628         else
629                 if type == "error" or type == "result" then return; end
630                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
631         end
632 end
633
634 function room_mt:handle_stanza(origin, stanza)
635         local to_node, to_host, to_resource = jid_split(stanza.attr.to);
636         if to_resource then
637                 self:handle_to_occupant(origin, stanza);
638         else
639                 self:handle_to_room(origin, stanza);
640         end
641 end
642
643 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
644
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
650         return result;
651 end
652 function room_mt:set_affiliation(actor, jid, affiliation, callback, reason)
653         jid = jid_bare(jid);
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";
657         end
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()
666                         :up();
667         local x = p.tags[1];
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
673                 else
674                         x:tag("status", {code="321"}):up(); -- affiliation change
675                 end
676         end
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;
682                         else
683                                 t_insert(modified_nicks, nick);
684                                 occupant.affiliation, occupant.role = affiliation, role;
685                         end
686                         p.attr.from = nick;
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
689                                 p.attr.to = jid;
690                                 self:_route_stanza(p);
691                         end
692                 end
693         end
694         if self.save then self:save(); end
695         if callback then callback(); end
696         for _, nick in ipairs(modified_nicks) do
697                 p.attr.from = nick;
698                 self:broadcast_except_nick(p, nick);
699         end
700         return true;
701 end
702
703 function room_mt:get_role(nick)
704         local session = self._occupants[nick];
705         return session and session.role or nil;
706 end
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()
718                         :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;
724                 end
725                 p:tag("status", {code = "307"}):up();
726         else
727                 occupant.role = role;
728         end
729         for jid in pairs(occupant.sessions) do -- send to all sessions of the nick
730                 p.attr.to = jid;
731                 self:_route_stanza(p);
732         end
733         if callback then callback(); end
734         self:broadcast_except_nick(p, nick);
735         return true;
736 end
737
738 function room_mt:_route_stanza(stanza)
739         local muc_child;
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
748                                                 muc_child = tag;
749                                                 break;
750                                         end
751                                 end
752                         end
753                 end
754         end
755         if muc_child 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;
760                                 else
761                                         item.attr.jid = from_occupant.jid;
762                                 end
763                         end
764                 end
765         end
766         self:route_stanza(stanza);
767         if muc_child then
768                 for _, item in pairs(muc_child.tags) do
769                         if item.name == "item" then
770                                 item.attr.jid = nil;
771                         end
772                 end
773         end
774 end
775
776 local _M = {}; -- module "muc"
777
778 function _M.new_room(jid)
779         return setmetatable({
780                 jid = jid;
781                 _jid_nick = {};
782                 _occupants = {};
783                 _data = {};
784                 _affiliations = {};
785         }, room_mt);
786 end
787
788 return _M;