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