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