647bf9152cd705c986f9594a412a19b06cae7dda
[prosody.git] / plugins / muc / muc.lib.lua
1 -- Prosody IM
2 -- Copyright (C) 2008-2010 Matthew Wild
3 -- Copyright (C) 2008-2010 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 select = select;
10 local pairs, ipairs = pairs, ipairs;
11
12 local datamanager = require "util.datamanager";
13 local datetime = require "util.datetime";
14
15 local dataform = require "util.dataforms";
16
17 local jid_split = require "util.jid".split;
18 local jid_bare = require "util.jid".bare;
19 local jid_prep = require "util.jid".prep;
20 local st = require "util.stanza";
21 local log = require "util.logger".init("mod_muc");
22 local multitable_new = require "util.multitable".new;
23 local t_insert, t_remove = table.insert, table.remove;
24 local setmetatable = setmetatable;
25 local base64 = require "util.encodings".base64;
26 local md5 = require "util.hashes".md5;
27
28 local muc_domain = nil; --module:get_host();
29 local default_history_length = 20;
30
31 ------------
32 local function filter_xmlns_from_array(array, filters)
33         local count = 0;
34         for i=#array,1,-1 do
35                 local attr = array[i].attr;
36                 if filters[attr and attr.xmlns] then
37                         t_remove(array, i);
38                         count = count + 1;
39                 end
40         end
41         return count;
42 end
43 local function filter_xmlns_from_stanza(stanza, filters)
44         if filters then
45                 if filter_xmlns_from_array(stanza.tags, filters) ~= 0 then
46                         return stanza, filter_xmlns_from_array(stanza, filters);
47                 end
48         end
49         return stanza, 0;
50 end
51 local presence_filters = {["http://jabber.org/protocol/muc"]=true;["http://jabber.org/protocol/muc#user"]=true};
52 local function get_filtered_presence(stanza)
53         return filter_xmlns_from_stanza(st.clone(stanza):reset(), presence_filters);
54 end
55 local kickable_error_conditions = {
56         ["gone"] = true;
57         ["internal-server-error"] = true;
58         ["item-not-found"] = true;
59         ["jid-malformed"] = true;
60         ["recipient-unavailable"] = true;
61         ["redirect"] = true;
62         ["remote-server-not-found"] = true;
63         ["remote-server-timeout"] = true;
64         ["service-unavailable"] = true;
65         ["malformed error"] = true;
66 };
67
68 local function get_error_condition(stanza)
69         local _, condition = stanza:get_error();
70         return condition or "malformed error";
71 end
72
73 local function is_kickable_error(stanza)
74         local cond = get_error_condition(stanza);
75         return kickable_error_conditions[cond] and cond;
76 end
77 local function getUsingPath(stanza, path, getText)
78         local tag = stanza;
79         for _, name in ipairs(path) do
80                 if type(tag) ~= 'table' then return; end
81                 tag = tag:child_with_name(name);
82         end
83         if tag and getText then tag = table.concat(tag); end
84         return tag;
85 end
86 local function getTag(stanza, path) return getUsingPath(stanza, path); end
87 local function getText(stanza, path) return getUsingPath(stanza, path, true); end
88 -----------
89
90 local room_mt = {};
91 room_mt.__index = room_mt;
92
93 function room_mt:get_default_role(affiliation)
94         if affiliation == "owner" or affiliation == "admin" then
95                 return "moderator";
96         elseif affiliation == "member" then
97                 return "participant";
98         elseif not affiliation then
99                 if not self:is_members_only() then
100                         return self:is_moderated() and "visitor" or "participant";
101                 end
102         end
103 end
104
105 function room_mt:broadcast_presence(stanza, sid, code, nick)
106         stanza = get_filtered_presence(stanza);
107         local occupant = self._occupants[stanza.attr.from];
108         stanza:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
109                 :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none", nick=nick}):up();
110         if code then
111                 stanza:tag("status", {code=code}):up();
112         end
113         self:broadcast_except_nick(stanza, stanza.attr.from);
114         local me = self._occupants[stanza.attr.from];
115         if me then
116                 stanza:tag("status", {code='110'}):up();
117                 stanza.attr.to = sid;
118                 self:_route_stanza(stanza);
119         end
120 end
121 function room_mt:broadcast_message(stanza, historic)
122         local to = stanza.attr.to;
123         for occupant, o_data in pairs(self._occupants) do
124                 for jid in pairs(o_data.sessions) do
125                         stanza.attr.to = jid;
126                         self:_route_stanza(stanza);
127                 end
128         end
129         stanza.attr.to = to;
130         if historic then -- add to history
131                 local history = self._data['history'];
132                 if not history then history = {}; self._data['history'] = history; end
133                 stanza = st.clone(stanza);
134                 stanza.attr.to = "";
135                 local stamp = datetime.datetime();
136                 local chars = #tostring(stanza);
137                 stanza:tag("delay", {xmlns = "urn:xmpp:delay", from = muc_domain, stamp = stamp}):up(); -- XEP-0203
138                 stanza:tag("x", {xmlns = "jabber:x:delay", from = muc_domain, stamp = datetime.legacy()}):up(); -- XEP-0091 (deprecated)
139                 local entry = { stanza = stanza, stamp = stamp };
140                 t_insert(history, entry);
141                 while #history > (self._data.history_length or default_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 or "none", role=o_data.role or "none"}):up();
163                         self:_route_stanza(pres);
164                 end
165         end
166 end
167 function room_mt:send_history(to, stanza)
168         local history = self._data['history']; -- send discussion history
169         if history then
170                 local x_tag = stanza and stanza:get_child("x", "http://jabber.org/protocol/muc");
171                 local history_tag = x_tag and x_tag:get_child("history", "http://jabber.org/protocol/muc");
172                 
173                 local maxchars = history_tag and tonumber(history_tag.attr.maxchars);
174                 if maxchars then maxchars = math.floor(maxchars); end
175                 
176                 local maxstanzas = math.floor(history_tag and tonumber(history_tag.attr.maxstanzas) or #history);
177                 if not history_tag then maxstanzas = 20; end
178
179                 local seconds = history_tag and tonumber(history_tag.attr.seconds);
180                 if seconds then seconds = datetime.datetime(os.time() - math.floor(seconds)); end
181
182                 local since = history_tag and history_tag.attr.since;
183                 if since then since = datetime.parse(since); since = since and datetime.datetime(since); end
184                 if seconds and (not since or since < seconds) then since = seconds; end
185
186                 local n = 0;
187                 local charcount = 0;
188                 local stanzacount = 0;
189                 
190                 for i=#history,1,-1 do
191                         local entry = history[i];
192                         if maxchars then
193                                 if not entry.chars then
194                                         entry.stanza.attr.to = "";
195                                         entry.chars = #tostring(entry.stanza);
196                                 end
197                                 charcount = charcount + entry.chars + #to;
198                                 if charcount > maxchars then break; end
199                         end
200                         if since and since > entry.stamp then break; end
201                         if n + 1 > maxstanzas then break; end
202                         n = n + 1;
203                 end
204                 for i=#history-n+1,#history do
205                         local msg = history[i].stanza;
206                         msg.attr.to = to;
207                         self:_route_stanza(msg);
208                 end
209         end
210         if self._data['subject'] then
211                 self:_route_stanza(st.message({type='groupchat', from=self._data['subject_from'] or self.jid, to=to}):tag("subject"):text(self._data['subject']));
212         end
213 end
214
215 function room_mt:get_disco_info(stanza)
216         return st.reply(stanza):query("http://jabber.org/protocol/disco#info")
217                 :tag("identity", {category="conference", type="text", name=self:get_name()}):up()
218                 :tag("feature", {var="http://jabber.org/protocol/muc"}):up()
219                 :tag("feature", {var=self:get_password() and "muc_passwordprotected" or "muc_unsecured"}):up()
220                 :tag("feature", {var=self:is_moderated() and "muc_moderated" or "muc_unmoderated"}):up()
221                 :tag("feature", {var=self:is_members_only() and "muc_membersonly" or "muc_open"}):up()
222                 :tag("feature", {var=self:is_persistent() and "muc_persistent" or "muc_temporary"}):up()
223                 :tag("feature", {var=self:is_hidden() and "muc_hidden" or "muc_public"}):up()
224                 :tag("feature", {var=self._data.whois ~= "anyone" and "muc_semianonymous" or "muc_nonanonymous"}):up()
225                 :add_child(dataform.new({
226                         { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" },
227                         { name = "muc#roominfo_description", label = "Description"}
228                 }):form({["muc#roominfo_description"] = self:get_description()}, 'result'))
229         ;
230 end
231 function room_mt:get_disco_items(stanza)
232         local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
233         for room_jid in pairs(self._occupants) do
234                 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
235         end
236         return reply;
237 end
238 function room_mt:set_subject(current_nick, subject)
239         -- TODO check nick's authority
240         if subject == "" then subject = nil; end
241         self._data['subject'] = subject;
242         self._data['subject_from'] = current_nick;
243         if self.save then self:save(); end
244         local msg = st.message({type='groupchat', from=current_nick})
245                 :tag('subject'):text(subject):up();
246         self:broadcast_message(msg, false);
247         return true;
248 end
249
250 local function build_unavailable_presence_from_error(stanza)
251         local type, condition, text = stanza:get_error();
252         local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
253         if text then
254                 error_message = error_message..": "..text;
255         end
256         return st.presence({type='unavailable', from=stanza.attr.from, to=stanza.attr.to})
257                 :tag('status'):text(error_message);
258 end
259
260 function room_mt:set_name(name)
261         if name == "" or type(name) ~= "string" or name == (jid_split(self.jid)) then name = nil; end
262         if self._data.name ~= name then
263                 self._data.name = name;
264                 if self.save then self:save(true); end
265         end
266 end
267 function room_mt:get_name()
268         return self._data.name or jid_split(self.jid);
269 end
270 function room_mt:set_description(description)
271         if description == "" or type(description) ~= "string" then description = nil; end
272         if self._data.description ~= description then
273                 self._data.description = description;
274                 if self.save then self:save(true); end
275         end
276 end
277 function room_mt:get_description()
278         return self._data.description;
279 end
280 function room_mt:set_password(password)
281         if password == "" or type(password) ~= "string" then password = nil; end
282         if self._data.password ~= password then
283                 self._data.password = password;
284                 if self.save then self:save(true); end
285         end
286 end
287 function room_mt:get_password()
288         return self._data.password;
289 end
290 function room_mt:set_moderated(moderated)
291         moderated = moderated and true or nil;
292         if self._data.moderated ~= moderated then
293                 self._data.moderated = moderated;
294                 if self.save then self:save(true); end
295         end
296 end
297 function room_mt:is_moderated()
298         return self._data.moderated;
299 end
300 function room_mt:set_members_only(members_only)
301         members_only = members_only and true or nil;
302         if self._data.members_only ~= members_only then
303                 self._data.members_only = members_only;
304                 if self.save then self:save(true); end
305         end
306 end
307 function room_mt:is_members_only()
308         return self._data.members_only;
309 end
310 function room_mt:set_persistent(persistent)
311         persistent = persistent and true or nil;
312         if self._data.persistent ~= persistent then
313                 self._data.persistent = persistent;
314                 if self.save then self:save(true); end
315         end
316 end
317 function room_mt:is_persistent()
318         return self._data.persistent;
319 end
320 function room_mt:set_hidden(hidden)
321         hidden = hidden and true or nil;
322         if self._data.hidden ~= hidden then
323                 self._data.hidden = hidden;
324                 if self.save then self:save(true); end
325         end
326 end
327 function room_mt:is_hidden()
328         return self._data.hidden;
329 end
330 function room_mt:set_changesubject(changesubject)
331         changesubject = changesubject and true or nil;
332         if self._data.changesubject ~= changesubject then
333                 self._data.changesubject = changesubject;
334                 if self.save then self:save(true); end
335         end
336 end
337 function room_mt:get_changesubject()
338         return self._data.changesubject;
339 end
340
341 function room_mt:handle_to_occupant(origin, stanza) -- PM, vCards, etc
342         local from, to = stanza.attr.from, stanza.attr.to;
343         local room = jid_bare(to);
344         local current_nick = self._jid_nick[from];
345         local type = stanza.attr.type;
346         log("debug", "room: %s, current_nick: %s, stanza: %s", room or "nil", current_nick or "nil", stanza:top_tag());
347         if (select(2, jid_split(from)) == muc_domain) then error("Presence from the MUC itself!!!"); end
348         if stanza.name == "presence" then
349                 local pr = get_filtered_presence(stanza);
350                 pr.attr.from = current_nick;
351                 if type == "error" then -- error, kick em out!
352                         if current_nick then
353                                 log("debug", "kicking %s from %s", current_nick, room);
354                                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza));
355                         end
356                 elseif type == "unavailable" then -- unavailable
357                         if current_nick then
358                                 log("debug", "%s leaving %s", current_nick, room);
359                                 local occupant = self._occupants[current_nick];
360                                 local new_jid = next(occupant.sessions);
361                                 if new_jid == from then new_jid = next(occupant.sessions, new_jid); end
362                                 if new_jid then
363                                         local jid = occupant.jid;
364                                         occupant.jid = new_jid;
365                                         occupant.sessions[from] = nil;
366                                         pr.attr.to = from;
367                                         pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
368                                                 :tag("item", {affiliation=occupant.affiliation or "none", role='none'}):up()
369                                                 :tag("status", {code='110'}):up();
370                                         self:_route_stanza(pr);
371                                         if jid ~= new_jid then
372                                                 pr = st.clone(occupant.sessions[new_jid])
373                                                         :tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
374                                                         :tag("item", {affiliation=occupant.affiliation or "none", role=occupant.role or "none"});
375                                                 pr.attr.from = current_nick;
376                                                 self:broadcast_except_nick(pr, current_nick);
377                                         end
378                                 else
379                                         occupant.role = 'none';
380                                         self:broadcast_presence(pr, from);
381                                         self._occupants[current_nick] = nil;
382                                 end
383                                 self._jid_nick[from] = nil;
384                         end
385                 elseif not type then -- available
386                         if current_nick then
387                                 --if #pr == #stanza or current_nick ~= to then -- commented because google keeps resending directed presence
388                                         if current_nick == to then -- simple presence
389                                                 log("debug", "%s broadcasted presence", current_nick);
390                                                 self._occupants[current_nick].sessions[from] = pr;
391                                                 self:broadcast_presence(pr, from);
392                                         else -- change nick
393                                                 local occupant = self._occupants[current_nick];
394                                                 local is_multisession = next(occupant.sessions, next(occupant.sessions));
395                                                 if self._occupants[to] or is_multisession then
396                                                         log("debug", "%s couldn't change nick", current_nick);
397                                                         local reply = st.error_reply(stanza, "cancel", "conflict"):up();
398                                                         reply.tags[1].attr.code = "409";
399                                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
400                                                 else
401                                                         local data = self._occupants[current_nick];
402                                                         local to_nick = select(3, jid_split(to));
403                                                         if to_nick then
404                                                                 log("debug", "%s (%s) changing nick to %s", current_nick, data.jid, to);
405                                                                 local p = st.presence({type='unavailable', from=current_nick});
406                                                                 self:broadcast_presence(p, from, '303', to_nick);
407                                                                 self._occupants[current_nick] = nil;
408                                                                 self._occupants[to] = data;
409                                                                 self._jid_nick[from] = to;
410                                                                 pr.attr.from = to;
411                                                                 self._occupants[to].sessions[from] = pr;
412                                                                 self:broadcast_presence(pr, from);
413                                                         else
414                                                                 --TODO malformed-jid
415                                                         end
416                                                 end
417                                         end
418                                 --else -- possible rejoin
419                                 --      log("debug", "%s had connection replaced", current_nick);
420                                 --      self:handle_to_occupant(origin, st.presence({type='unavailable', from=from, to=to})
421                                 --              :tag('status'):text('Replaced by new connection'):up()); -- send unavailable
422                                 --      self:handle_to_occupant(origin, stanza); -- resend available
423                                 --end
424                         else -- enter room
425                                 local new_nick = to;
426                                 local is_merge;
427                                 if self._occupants[to] then
428                                         if jid_bare(from) ~= jid_bare(self._occupants[to].jid) then
429                                                 new_nick = nil;
430                                         end
431                                         is_merge = true;
432                                 end
433                                 local password = stanza:get_child("x", "http://jabber.org/protocol/muc");
434                                 password = password and password:get_child("password", "http://jabber.org/protocol/muc");
435                                 password = password and password[1] ~= "" and password[1];
436                                 if self:get_password() and self:get_password() ~= password then
437                                         log("debug", "%s couldn't join due to invalid password: %s", from, to);
438                                         local reply = st.error_reply(stanza, "auth", "not-authorized"):up();
439                                         reply.tags[1].attr.code = "401";
440                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
441                                 elseif not new_nick then
442                                         log("debug", "%s couldn't join due to nick conflict: %s", from, to);
443                                         local reply = st.error_reply(stanza, "cancel", "conflict"):up();
444                                         reply.tags[1].attr.code = "409";
445                                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
446                                 else
447                                         log("debug", "%s joining as %s", from, to);
448                                         if not next(self._affiliations) then -- new room, no owners
449                                                 self._affiliations[jid_bare(from)] = "owner";
450                                         end
451                                         local affiliation = self:get_affiliation(from);
452                                         local role = self:get_default_role(affiliation)
453                                         if role then -- new occupant
454                                                 if not is_merge then
455                                                         self._occupants[to] = {affiliation=affiliation, role=role, jid=from, sessions={[from]=get_filtered_presence(stanza)}};
456                                                 else
457                                                         self._occupants[to].sessions[from] = get_filtered_presence(stanza);
458                                                 end
459                                                 self._jid_nick[from] = to;
460                                                 self:send_occupant_list(from);
461                                                 pr.attr.from = to;
462                                                 pr:tag("x", {xmlns='http://jabber.org/protocol/muc#user'})
463                                                         :tag("item", {affiliation=affiliation or "none", role=role or "none"}):up();
464                                                 if not is_merge then
465                                                         self:broadcast_except_nick(pr, to);
466                                                 end
467                                                 pr:tag("status", {code='110'}):up();
468                                                 if self._data.whois == 'anyone' then
469                                                         pr:tag("status", {code='100'}):up();
470                                                 end
471                                                 pr.attr.to = from;
472                                                 self:_route_stanza(pr);
473                                                 self:send_history(from, stanza);
474                                         elseif not affiliation then -- registration required for entering members-only room
475                                                 local reply = st.error_reply(stanza, "auth", "registration-required"):up();
476                                                 reply.tags[1].attr.code = "407";
477                                                 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
478                                         else -- banned
479                                                 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
480                                                 reply.tags[1].attr.code = "403";
481                                                 origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
482                                         end
483                                 end
484                         end
485                 elseif type ~= 'result' then -- bad type
486                         if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
487                                 origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
488                         end
489                 end
490         elseif not current_nick then -- not in room
491                 if type == "error" or type == "result" then
492                         local id = stanza.name == "iq" and stanza.attr.id and base64.decode(stanza.attr.id);
493                         local _nick, _id, _hash = (id or ""):match("^(.+)%z(.*)%z(.+)$");
494                         local occupant = self._occupants[stanza.attr.to];
495                         if occupant and _nick and self._jid_nick[_nick] and _id and _hash then
496                                 local id, _to = stanza.attr.id;
497                                 for jid in pairs(occupant.sessions) do
498                                         if md5(jid) == _hash then
499                                                 _to = jid;
500                                                 break;
501                                         end
502                                 end
503                                 if _to then
504                                         stanza.attr.to, stanza.attr.from, stanza.attr.id = _to, self._jid_nick[_nick], _id;
505                                         self:_route_stanza(stanza);
506                                         stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
507                                 end
508                         end
509                 else
510                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
511                 end
512         elseif stanza.name == "message" and type == "groupchat" then -- groupchat messages not allowed in PM
513                 origin.send(st.error_reply(stanza, "modify", "bad-request"));
514         elseif current_nick and stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
515                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
516                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
517         else -- private stanza
518                 local o_data = self._occupants[to];
519                 if o_data then
520                         log("debug", "%s sent private stanza to %s (%s)", from, to, o_data.jid);
521                         local jid = o_data.jid;
522                         local bare = jid_bare(jid);
523                         stanza.attr.to, stanza.attr.from = jid, current_nick;
524                         local id = stanza.attr.id;
525                         if stanza.name=='iq' and type=='get' and stanza.tags[1].attr.xmlns == 'vcard-temp' and bare ~= jid then
526                                 stanza.attr.to = bare;
527                                 stanza.attr.id = base64.encode(jid.."\0"..id.."\0"..md5(from));
528                         end
529                         self:_route_stanza(stanza);
530                         stanza.attr.to, stanza.attr.from, stanza.attr.id = to, from, id;
531                 elseif type ~= "error" and type ~= "result" then -- recipient not in room
532                         origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
533                 end
534         end
535 end
536
537 function room_mt:send_form(origin, stanza)
538         origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
539                 :add_child(self:get_form_layout():form())
540         );
541 end
542
543 function room_mt:get_form_layout()
544         local title = "Configuration for "..self.jid;
545         return dataform.new({
546                 title = title,
547                 instructions = title,
548                 {
549                         name = 'FORM_TYPE',
550                         type = 'hidden',
551                         value = 'http://jabber.org/protocol/muc#roomconfig'
552                 },
553                 {
554                         name = 'muc#roomconfig_roomname',
555                         type = 'text-single',
556                         label = 'Name',
557                         value = self:get_name() or "",
558                 },
559                 {
560                         name = 'muc#roomconfig_roomdesc',
561                         type = 'text-single',
562                         label = 'Description',
563                         value = self:get_description() or "",
564                 },
565                 {
566                         name = 'muc#roomconfig_persistentroom',
567                         type = 'boolean',
568                         label = 'Make Room Persistent?',
569                         value = self:is_persistent()
570                 },
571                 {
572                         name = 'muc#roomconfig_publicroom',
573                         type = 'boolean',
574                         label = 'Make Room Publicly Searchable?',
575                         value = not self:is_hidden()
576                 },
577                 {
578                         name = 'muc#roomconfig_changesubject',
579                         type = 'boolean',
580                         label = 'Allow Occupants to Change Subject?',
581                         value = self:get_changesubject()
582                 },
583                 {
584                         name = 'muc#roomconfig_whois',
585                         type = 'list-single',
586                         label = 'Who May Discover Real JIDs?',
587                         value = {
588                                 { value = 'moderators', label = 'Moderators Only', default = self._data.whois == 'moderators' },
589                                 { value = 'anyone',     label = 'Anyone',          default = self._data.whois == 'anyone' }
590                         }
591                 },
592                 {
593                         name = 'muc#roomconfig_roomsecret',
594                         type = 'text-private',
595                         label = 'Password',
596                         value = self:get_password() or "",
597                 },
598                 {
599                         name = 'muc#roomconfig_moderatedroom',
600                         type = 'boolean',
601                         label = 'Make Room Moderated?',
602                         value = self:is_moderated()
603                 },
604                 {
605                         name = 'muc#roomconfig_membersonly',
606                         type = 'boolean',
607                         label = 'Make Room Members-Only?',
608                         value = self:is_members_only()
609                 }
610         });
611 end
612
613 local valid_whois = {
614         moderators = true,
615         anyone = true,
616 }
617
618 function room_mt:process_form(origin, stanza)
619         local query = stanza.tags[1];
620         local form;
621         for _, tag in ipairs(query.tags) do if tag.name == "x" and tag.attr.xmlns == "jabber:x:data" then form = tag; break; end end
622         if not form then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); return; end
623         if form.attr.type == "cancel" then origin.send(st.reply(stanza)); return; end
624         if form.attr.type ~= "submit" then origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form")); return; end
625
626         local fields = self:get_form_layout():data(form);
627         if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration")); return; end
628
629         local dirty = false
630
631         local name = fields['muc#roomconfig_roomname'];
632         if name ~= self:get_name() then
633                 self:set_name(name);
634         end
635
636         local description = fields['muc#roomconfig_roomdesc'];
637         if description ~= self:get_description() then
638                 self:set_description(description);
639         end
640
641         local persistent = fields['muc#roomconfig_persistentroom'];
642         dirty = dirty or (self:is_persistent() ~= persistent)
643         module:log("debug", "persistent=%s", tostring(persistent));
644
645         local moderated = fields['muc#roomconfig_moderatedroom'];
646         dirty = dirty or (self:is_moderated() ~= moderated)
647         module:log("debug", "moderated=%s", tostring(moderated));
648
649         local membersonly = fields['muc#roomconfig_membersonly'];
650         dirty = dirty or (self:is_members_only() ~= membersonly)
651         module:log("debug", "membersonly=%s", tostring(membersonly));
652
653         local public = fields['muc#roomconfig_publicroom'];
654         dirty = dirty or (self:is_hidden() ~= (not public and true or nil))
655
656         local changesubject = fields['muc#roomconfig_changesubject'];
657         dirty = dirty or (self:get_changesubject() ~= (not changesubject and true or nil))
658         module:log('debug', 'changesubject=%s', changesubject and "true" or "false")
659
660         local whois = fields['muc#roomconfig_whois'];
661         if not valid_whois[whois] then
662             origin.send(st.error_reply(stanza, 'cancel', 'bad-request', "Invalid value for 'whois'"));
663             return;
664         end
665         local whois_changed = self._data.whois ~= whois
666         self._data.whois = whois
667         module:log('debug', 'whois=%s', whois)
668
669         local password = fields['muc#roomconfig_roomsecret'];
670         if self:get_password() ~= password then
671                 self:set_password(password);
672         end
673         self:set_moderated(moderated);
674         self:set_members_only(membersonly);
675         self:set_persistent(persistent);
676         self:set_hidden(not public);
677         self:set_changesubject(changesubject);
678
679         if self.save then self:save(true); end
680         origin.send(st.reply(stanza));
681
682         if dirty or whois_changed then
683                 local msg = st.message({type='groupchat', from=self.jid})
684                         :tag('x', {xmlns='http://jabber.org/protocol/muc#user'}):up()
685
686                 if dirty then
687                         msg.tags[1]:tag('status', {code = '104'}):up();
688                 end
689                 if whois_changed then
690                         local code = (whois == 'moderators') and "173" or "172";
691                         msg.tags[1]:tag('status', {code = code}):up();
692                 end
693
694                 self:broadcast_message(msg, false)
695         end
696 end
697
698 function room_mt:destroy(newjid, reason, password)
699         local pr = st.presence({type = "unavailable"})
700                 :tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
701                         :tag("item", { affiliation='none', role='none' }):up()
702                         :tag("destroy", {jid=newjid})
703         if reason then pr:tag("reason"):text(reason):up(); end
704         if password then pr:tag("password"):text(password):up(); end
705         for nick, occupant in pairs(self._occupants) do
706                 pr.attr.from = nick;
707                 for jid in pairs(occupant.sessions) do
708                         pr.attr.to = jid;
709                         self:_route_stanza(pr);
710                         self._jid_nick[jid] = nil;
711                 end
712                 self._occupants[nick] = nil;
713         end
714         self:set_persistent(false);
715 end
716
717 function room_mt:handle_to_room(origin, stanza) -- presence changes and groupchat messages, along with disco/etc
718         local type = stanza.attr.type;
719         local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns;
720         if stanza.name == "iq" then
721                 if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" then
722                         origin.send(self:get_disco_info(stanza));
723                 elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" then
724                         origin.send(self:get_disco_items(stanza));
725                 elseif xmlns == "http://jabber.org/protocol/muc#admin" then
726                         local actor = stanza.attr.from;
727                         local affiliation = self:get_affiliation(actor);
728                         local current_nick = self._jid_nick[actor];
729                         local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation);
730                         local item = stanza.tags[1].tags[1];
731                         if item and item.name == "item" then
732                                 if type == "set" then
733                                         local callback = function() origin.send(st.reply(stanza)); end
734                                         if item.attr.jid then -- Validate provided JID
735                                                 item.attr.jid = jid_prep(item.attr.jid);
736                                                 if not item.attr.jid then
737                                                         origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
738                                                         return;
739                                                 end
740                                         end
741                                         if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
742                                                 local occupant = self._occupants[self.jid.."/"..item.attr.nick];
743                                                 if occupant then item.attr.jid = occupant.jid; end
744                                         elseif not item.attr.nick and item.attr.jid then
745                                                 local nick = self._jid_nick[item.attr.jid];
746                                                 if nick then item.attr.nick = select(3, jid_split(nick)); end
747                                         end
748                                         local reason = item.tags[1] and item.tags[1].name == "reason" and #item.tags[1] == 1 and item.tags[1][1];
749                                         if item.attr.affiliation and item.attr.jid and not item.attr.role then
750                                                 local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback, reason);
751                                                 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
752                                         elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
753                                                 local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback, reason);
754                                                 if not success then origin.send(st.error_reply(stanza, errtype, err)); end
755                                         else
756                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
757                                         end
758                                 elseif type == "get" then
759                                         local _aff = item.attr.affiliation;
760                                         local _rol = item.attr.role;
761                                         if _aff and not _rol then
762                                                 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
763                                                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
764                                                         for jid, affiliation in pairs(self._affiliations) do
765                                                                 if affiliation == _aff then
766                                                                         reply:tag("item", {affiliation = _aff, jid = jid}):up();
767                                                                 end
768                                                         end
769                                                         origin.send(reply);
770                                                 else
771                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
772                                                 end
773                                         elseif _rol and not _aff then
774                                                 if role == "moderator" then
775                                                         -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway?
776                                                         if _rol == "none" then _rol = nil; end
777                                                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
778                                                         for occupant_jid, occupant in pairs(self._occupants) do
779                                                                 if occupant.role == _rol then
780                                                                         reply:tag("item", {
781                                                                                 nick = select(3, jid_split(occupant_jid)),
782                                                                                 role = _rol or "none",
783                                                                                 affiliation = occupant.affiliation or "none",
784                                                                                 jid = occupant.jid
785                                                                                 }):up();
786                                                                 end
787                                                         end
788                                                         origin.send(reply);
789                                                 else
790                                                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
791                                                 end
792                                         else
793                                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
794                                         end
795                                 end
796                         elseif type == "set" or type == "get" then
797                                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
798                         end
799                 elseif xmlns == "http://jabber.org/protocol/muc#owner" and (type == "get" or type == "set") and stanza.tags[1].name == "query" then
800                         if self:get_affiliation(stanza.attr.from) ~= "owner" then
801                                 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
802                         elseif stanza.attr.type == "get" then
803                                 self:send_form(origin, stanza);
804                         elseif stanza.attr.type == "set" then
805                                 local child = stanza.tags[1].tags[1];
806                                 if not child then
807                                         origin.send(st.error_reply(stanza, "auth", "bad-request"));
808                                 elseif child.name == "destroy" then
809                                         local newjid = child.attr.jid;
810                                         local reason, password;
811                                         for _,tag in ipairs(child.tags) do
812                                                 if tag.name == "reason" then
813                                                         reason = #tag.tags == 0 and tag[1];
814                                                 elseif tag.name == "password" then
815                                                         password = #tag.tags == 0 and tag[1];
816                                                 end
817                                         end
818                                         self:destroy(newjid, reason, password);
819                                         origin.send(st.reply(stanza));
820                                 else
821                                         self:process_form(origin, stanza);
822                                 end
823                         end
824                 elseif type == "set" or type == "get" then
825                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
826                 end
827         elseif stanza.name == "message" and type == "groupchat" then
828                 local from, to = stanza.attr.from, stanza.attr.to;
829                 local room = jid_bare(to);
830                 local current_nick = self._jid_nick[from];
831                 local occupant = self._occupants[current_nick];
832                 if not occupant then -- not in room
833                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
834                 elseif occupant.role == "visitor" then
835                         origin.send(st.error_reply(stanza, "cancel", "forbidden"));
836                 else
837                         local from = stanza.attr.from;
838                         stanza.attr.from = current_nick;
839                         local subject = getText(stanza, {"subject"});
840                         if subject then
841                                 if occupant.role == "moderator" or
842                                         ( self._data.changesubject and occupant.role == "participant" ) then -- and participant
843                                         self:set_subject(current_nick, subject); -- TODO use broadcast_message_stanza
844                                 else
845                                         stanza.attr.from = from;
846                                         origin.send(st.error_reply(stanza, "cancel", "forbidden"));
847                                 end
848                         else
849                                 self:broadcast_message(stanza, true);
850                         end
851                         stanza.attr.from = from;
852                 end
853         elseif stanza.name == "message" and type == "error" and is_kickable_error(stanza) then
854                 local current_nick = self._jid_nick[stanza.attr.from];
855                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
856                 self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable
857         elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick
858                 local to = stanza.attr.to;
859                 local current_nick = self._jid_nick[stanza.attr.from];
860                 if current_nick then
861                         stanza.attr.to = current_nick;
862                         self:handle_to_occupant(origin, stanza);
863                         stanza.attr.to = to;
864                 elseif type ~= "error" and type ~= "result" then
865                         origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
866                 end
867         elseif stanza.name == "message" and not stanza.attr.type and #stanza.tags == 1 and self._jid_nick[stanza.attr.from]
868                 and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" then
869                 local x = stanza.tags[1];
870                 local payload = (#x.tags == 1 and x.tags[1]);
871                 if payload and payload.name == "invite" and payload.attr.to then
872                         local _from, _to = stanza.attr.from, stanza.attr.to;
873                         local _invitee = jid_prep(payload.attr.to);
874                         if _invitee then
875                                 local _reason = payload.tags[1] and payload.tags[1].name == 'reason' and #payload.tags[1].tags == 0 and payload.tags[1][1];
876                                 local invite = st.message({from = _to, to = _invitee, id = stanza.attr.id})
877                                         :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
878                                                 :tag('invite', {from=_from})
879                                                         :tag('reason'):text(_reason or ""):up()
880                                                 :up();
881                                                 if self:get_password() then
882                                                         invite:tag("password"):text(self:get_password()):up();
883                                                 end
884                                         invite:up()
885                                         :tag('x', {xmlns="jabber:x:conference", jid=_to}) -- COMPAT: Some older clients expect this
886                                                 :text(_reason or "")
887                                         :up()
888                                         :tag('body') -- Add a plain message for clients which don't support invites
889                                                 :text(_from..' invited you to the room '.._to..(_reason and (' ('.._reason..')') or ""))
890                                         :up();
891                                 if self:is_members_only() and not self:get_affiliation(_invitee) then
892                                         log("debug", "%s invited %s into members only room %s, granting membership", _from, _invitee, _to);
893                                         self:set_affiliation(_from, _invitee, "member", nil, "Invited by " .. self._jid_nick[_from])
894                                 end
895                                 self:_route_stanza(invite);
896                         else
897                                 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
898                         end
899                 else
900                         origin.send(st.error_reply(stanza, "cancel", "bad-request"));
901                 end
902         else
903                 if type == "error" or type == "result" then return; end
904                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
905         end
906 end
907
908 function room_mt:handle_stanza(origin, stanza)
909         local to_node, to_host, to_resource = jid_split(stanza.attr.to);
910         if to_resource then
911                 self:handle_to_occupant(origin, stanza);
912         else
913                 self:handle_to_room(origin, stanza);
914         end
915 end
916
917 function room_mt:route_stanza(stanza) end -- Replace with a routing function, e.g., function(room, stanza) core_route_stanza(origin, stanza); end
918
919 function room_mt:get_affiliation(jid)
920         local node, host, resource = jid_split(jid);
921         local bare = node and node.."@"..host or host;
922         local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
923         if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
924         return result;
925 end
926 function room_mt:set_affiliation(actor, jid, affiliation, callback, reason)
927         jid = jid_bare(jid);
928         if affiliation == "none" then affiliation = nil; end
929         if affiliation and affiliation ~= "outcast" and affiliation ~= "owner" and affiliation ~= "admin" and affiliation ~= "member" then
930                 return nil, "modify", "not-acceptable";
931         end
932         local actor_affiliation = self:get_affiliation(actor);
933         local target_affiliation = self:get_affiliation(jid);
934         if target_affiliation == affiliation then -- no change, shortcut
935                 if callback then callback(); end
936                 return true;
937         end
938         if actor_affiliation ~= "owner" then
939                 if actor_affiliation ~= "admin" or target_affiliation == "owner" or target_affiliation == "admin" then
940                         return nil, "cancel", "not-allowed";
941                 end
942         elseif target_affiliation == "owner" and jid_bare(actor) == jid then -- self change
943                 local is_last = true;
944                 for j, aff in pairs(self._affiliations) do if j ~= jid and aff == "owner" then is_last = false; break; end end
945                 if is_last then
946                         return nil, "cancel", "conflict";
947                 end
948         end
949         self._affiliations[jid] = affiliation;
950         local role = self:get_default_role(affiliation);
951         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
952                         :tag("item", {affiliation=affiliation or "none", role=role or "none"})
953                                 :tag("reason"):text(reason or ""):up()
954                         :up();
955         local presence_type = nil;
956         if not role then -- getting kicked
957                 presence_type = "unavailable";
958                 if affiliation == "outcast" then
959                         x:tag("status", {code="301"}):up(); -- banned
960                 else
961                         x:tag("status", {code="321"}):up(); -- affiliation change
962                 end
963         end
964         local modified_nicks = {};
965         for nick, occupant in pairs(self._occupants) do
966                 if jid_bare(occupant.jid) == jid then
967                         if not role then -- getting kicked
968                                 self._occupants[nick] = nil;
969                         else
970                                 occupant.affiliation, occupant.role = affiliation, role;
971                         end
972                         for jid,pres in pairs(occupant.sessions) do -- remove for all sessions of the nick
973                                 if not role then self._jid_nick[jid] = nil; end
974                                 local p = st.clone(pres);
975                                 p.attr.from = nick;
976                                 p.attr.type = presence_type;
977                                 p.attr.to = jid;
978                                 p:add_child(x);
979                                 self:_route_stanza(p);
980                                 if occupant.jid == jid then
981                                         modified_nicks[nick] = p;
982                                 end
983                         end
984                 end
985         end
986         if self.save then self:save(); end
987         if callback then callback(); end
988         for nick,p in pairs(modified_nicks) do
989                 p.attr.from = nick;
990                 self:broadcast_except_nick(p, nick);
991         end
992         return true;
993 end
994
995 function room_mt:get_role(nick)
996         local session = self._occupants[nick];
997         return session and session.role or nil;
998 end
999 function room_mt:can_set_role(actor_jid, occupant_jid, role)
1000         local actor = self._occupants[self._jid_nick[actor_jid]];
1001         local occupant = self._occupants[occupant_jid];
1002         
1003         if not occupant or not actor then return nil, "modify", "not-acceptable"; end
1004
1005         if actor.role == "moderator" then
1006                 if occupant.affiliation ~= "owner" and occupant.affiliation ~= "admin" then
1007                         if actor.affiliation == "owner" or actor.affiliation == "admin" then
1008                                 return true;
1009                         elseif occupant.role ~= "moderator" and role ~= "moderator" then
1010                                 return true;
1011                         end
1012                 end
1013         end
1014         return nil, "cancel", "not-allowed";
1015 end
1016 function room_mt:set_role(actor, occupant_jid, role, callback, reason)
1017         if role == "none" then role = nil; end
1018         if role and role ~= "moderator" and role ~= "participant" and role ~= "visitor" then return nil, "modify", "not-acceptable"; end
1019         local allowed, err_type, err_condition = self:can_set_role(actor, occupant_jid, role);
1020         if not allowed then return allowed, err_type, err_condition; end
1021         local occupant = self._occupants[occupant_jid];
1022         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
1023                         :tag("item", {affiliation=occupant.affiliation or "none", nick=select(3, jid_split(occupant_jid)), role=role or "none"})
1024                                 :tag("reason"):text(reason or ""):up()
1025                         :up();
1026         local presence_type = nil;
1027         if not role then -- kick
1028                 presence_type = "unavailable";
1029                 self._occupants[occupant_jid] = nil;
1030                 for jid in pairs(occupant.sessions) do -- remove for all sessions of the nick
1031                         self._jid_nick[jid] = nil;
1032                 end
1033                 x:tag("status", {code = "307"}):up();
1034         else
1035                 occupant.role = role;
1036         end
1037         local bp;
1038         for jid,pres in pairs(occupant.sessions) do -- send to all sessions of the nick
1039                 local p = st.clone(pres);
1040                 p.attr.from = occupant_jid;
1041                 p.attr.type = presence_type;
1042                 p.attr.to = jid;
1043                 p:add_child(x);
1044                 self:_route_stanza(p);
1045                 if occupant.jid == jid then
1046                         bp = p;
1047                 end
1048         end
1049         if callback then callback(); end
1050         if bp then
1051                 self:broadcast_except_nick(bp, occupant_jid);
1052         end
1053         return true;
1054 end
1055
1056 function room_mt:_route_stanza(stanza)
1057         local muc_child;
1058         local to_occupant = self._occupants[self._jid_nick[stanza.attr.to]];
1059         local from_occupant = self._occupants[stanza.attr.from];
1060         if stanza.name == "presence" then
1061                 if to_occupant and from_occupant then
1062                         if self._data.whois == 'anyone' then
1063                             muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1064                         else
1065                                 if to_occupant.role == "moderator" or jid_bare(to_occupant.jid) == jid_bare(from_occupant.jid) then
1066                                         muc_child = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
1067                                 end
1068                         end
1069                 end
1070         end
1071         if muc_child then
1072                 for _, item in pairs(muc_child.tags) do
1073                         if item.name == "item" then
1074                                 if from_occupant == to_occupant then
1075                                         item.attr.jid = stanza.attr.to;
1076                                 else
1077                                         item.attr.jid = from_occupant.jid;
1078                                 end
1079                         end
1080                 end
1081         end
1082         self:route_stanza(stanza);
1083         if muc_child then
1084                 for _, item in pairs(muc_child.tags) do
1085                         if item.name == "item" then
1086                                 item.attr.jid = nil;
1087                         end
1088                 end
1089         end
1090 end
1091
1092 local _M = {}; -- module "muc"
1093
1094 function _M.new_room(jid, config)
1095         return setmetatable({
1096                 jid = jid;
1097                 _jid_nick = {};
1098                 _occupants = {};
1099                 _data = {
1100                     whois = 'moderators';
1101                     history_length = (config and config.history_length);
1102                 };
1103                 _affiliations = {};
1104         }, room_mt);
1105 end
1106
1107 return _M;