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