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