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