ad3800a7c53a0926756ee85dd08ed677c560bc35
[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 local next = next;
13 local setmetatable = setmetatable;
14
15 local dataform = require "util.dataforms";
16 local iterators = require "util.iterators";
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 base64 = require "util.encodings".base64;
23 local md5 = require "util.hashes".md5;
24
25 local occupant_lib = module:require "muc/occupant"
26 local muc_util = module:require "muc/util";
27 local is_kickable_error = muc_util.is_kickable_error;
28 local valid_roles, valid_affiliations = muc_util.valid_roles, muc_util.valid_affiliations;
29
30 local room_mt = {};
31 room_mt.__index = room_mt;
32
33 function room_mt:__tostring()
34         return "MUC room ("..self.jid..")";
35 end
36
37 function room_mt:get_occupant_jid(real_jid)
38         return self._jid_nick[real_jid]
39 end
40
41 function room_mt:get_default_role(affiliation)
42         local role = module:fire_event("muc-get-default-role", {
43                 room = self;
44                 affiliation = affiliation;
45                 affiliation_rank = valid_affiliations[affiliation or "none"];
46         });
47         return role, valid_roles[role or "none"];
48 end
49 module:hook("muc-get-default-role", function(event)
50         if event.affiliation_rank >= valid_affiliations.admin then
51                 return "moderator";
52         elseif event.affiliation_rank >= valid_affiliations.none then
53                 return "participant";
54         end
55 end);
56
57 --- Occupant functions
58 function room_mt:new_occupant(bare_real_jid, nick)
59         local occupant = occupant_lib.new(bare_real_jid, nick);
60         local affiliation = self:get_affiliation(bare_real_jid);
61         occupant.role = self:get_default_role(affiliation);
62         return occupant;
63 end
64
65 function room_mt:get_occupant_by_nick(nick)
66         local occupant = self._occupants[nick];
67         if occupant == nil then return nil end
68         return occupant_lib.copy(occupant);
69 end
70
71 do
72         local function next_copied_occupant(occupants, occupant_jid)
73                 local next_occupant_jid, raw_occupant = next(occupants, occupant_jid);
74                 if next_occupant_jid == nil then return nil end
75                 return next_occupant_jid, occupant_lib.copy(raw_occupant);
76         end
77         function room_mt:each_occupant(read_only)
78                 return next_copied_occupant, self._occupants, nil;
79         end
80 end
81
82 function room_mt:has_occupant()
83         return next(self._occupants, nil) ~= nil
84 end
85
86 function room_mt:get_occupant_by_real_jid(real_jid)
87         local occupant_jid = self:get_occupant_jid(real_jid);
88         if occupant_jid == nil then return nil end
89         return self:get_occupant_by_nick(occupant_jid);
90 end
91
92 function room_mt:save_occupant(occupant)
93         occupant = occupant_lib.copy(occupant); -- So that occupant can be modified more
94         local id = occupant.nick
95
96         -- Need to maintain _jid_nick secondary index
97         local old_occupant = self._occupants[id];
98         if old_occupant then
99                 for real_jid in old_occupant:each_session() do
100                         self._jid_nick[real_jid] = nil;
101                 end
102         end
103
104         local has_live_session = false
105         if occupant.role ~= nil then
106                 for real_jid, presence in occupant:each_session() do
107                         if presence.attr.type == nil then
108                                 has_live_session = true
109                                 self._jid_nick[real_jid] = occupant.nick;
110                         end
111                 end
112                 if not has_live_session then
113                         -- Has no live sessions left; they have left the room.
114                         occupant.role = nil
115                 end
116         end
117         if not has_live_session then
118                 occupant = nil
119         end
120         self._occupants[id] = occupant
121 end
122
123 function room_mt:route_to_occupant(occupant, stanza)
124         local to = stanza.attr.to;
125         for jid, pr in occupant:each_session() do
126                 stanza.attr.to = jid;
127                 self:route_stanza(stanza);
128         end
129         stanza.attr.to = to;
130 end
131
132 -- actor is the attribute table
133 local function add_item(x, affiliation, role, jid, nick, actor, reason)
134         x:tag("item", {affiliation = affiliation; role = role; jid = jid; nick = nick;})
135         if actor then
136                 x:tag("actor", actor):up()
137         end
138         if reason then
139                 x:tag("reason"):text(reason):up()
140         end
141         x:up();
142         return x
143 end
144
145 -- actor is (real) jid
146 function room_mt:build_item_list(occupant, x, is_anonymous, nick, actor, reason)
147         local affiliation = self:get_affiliation(occupant.bare_jid) or "none";
148         local role = occupant.role or "none";
149         local actor_attr;
150         if actor then
151                 actor_attr = {nick = select(3,jid_split(self:get_occupant_jid(actor)))};
152         end
153         if is_anonymous then
154                 add_item(x, affiliation, role, nil, nick, actor_attr, reason);
155         else
156                 if actor_attr then
157                         actor_attr.jid = actor;
158                 end
159                 for real_jid, session in occupant:each_session() do
160                         add_item(x, affiliation, role, real_jid, nick, actor_attr, reason);
161                 end
162         end
163         return x
164 end
165
166 function room_mt:broadcast_message(stanza)
167         if module:fire_event("muc-broadcast-message", {room = self, stanza = stanza}) then
168                 return true;
169         end
170         self:broadcast(stanza);
171         return true;
172 end
173
174 -- Broadcast a stanza to all occupants in the room.
175 -- optionally checks conditional called with (nick, occupant)
176 function room_mt:broadcast(stanza, cond_func)
177         for nick, occupant in self:each_occupant() do
178                 if cond_func == nil or cond_func(nick, occupant) then
179                         self:route_to_occupant(occupant, stanza)
180                 end
181         end
182 end
183
184 local function can_see_real_jids(whois, occupant)
185         if whois == "anyone" then
186                 return true;
187         elseif whois == "moderators" then
188                 return valid_roles[occupant.role or "none"] >= valid_roles.moderator;
189         end
190 end
191
192 -- Broadcasts an occupant's presence to the whole room
193 -- Takes the x element that goes into the stanzas
194 function room_mt:publicise_occupant_status(occupant, base_x, nick, actor, reason)
195         -- Build real jid and (optionally) occupant jid template presences
196         local base_presence;
197         if occupant.role ~= nil then
198                 -- Try to use main jid's presence
199                 local pr = occupant:get_presence();
200                 if pr ~= nil then
201                         base_presence = st.clone(pr);
202                 end
203         end
204         base_presence = base_presence or st.presence {from = occupant.nick; type = "unavailable";};
205
206         -- Fire event (before full_p and anon_p are created)
207         module:fire_event("muc-broadcast-presence", {
208                 room = self; stanza = base_presence; x = base_x;
209                 occupant = occupant; nick = nick; actor = actor;
210                 reason = reason;
211         });
212
213         local function get_presence(is_anonymous)
214                 local x = st.clone(base_x);
215                 self:build_item_list(occupant, x, is_anonymous, nick, actor, reason);
216                 return st.clone(base_presence):add_child(x), x;
217         end
218
219         local full_p, full_x = get_presence(false);
220
221         -- Create anon_p lazily
222         local anon_p, anon_x;
223         local function get_anon_p()
224                 if anon_p == nil then
225                         anon_p, anon_x = get_presence(true);
226                 end
227                 return anon_p, anon_x;
228         end
229
230         local whois = self:get_whois();
231
232         -- General populance
233         for nick, n_occupant in self:each_occupant() do
234                 if nick ~= occupant.nick then
235                         local pr;
236                         if can_see_real_jids(whois, n_occupant) or occupant.bare_jid == n_occupant.bare_jid then
237                                 pr = full_p;
238                         else
239                                 pr = get_anon_p();
240                         end
241                         self:route_to_occupant(n_occupant, pr);
242                 end
243         end
244
245         -- Presences for occupant itself
246         full_x:tag("status", {code = "110";}):up();
247         if occupant.role == nil then
248                 -- They get an unavailable
249                 self:route_to_occupant(occupant, full_p);
250         else
251                 -- use their own presences as templates
252                 for full_jid, pr in occupant:each_session() do
253                         pr = st.clone(pr);
254                         pr.attr.to = full_jid;
255                         -- You can always see your own full jids
256                         pr:add_child(full_x);
257                         self:route_stanza(pr);
258                 end
259         end
260 end
261
262 function room_mt:send_occupant_list(to, filter)
263         local to_bare = jid_bare(to);
264         local is_anonymous = false;
265         local whois = self:get_whois();
266         if whois ~= "anyone" then
267                 local affiliation = self:get_affiliation(to);
268                 if affiliation ~= "admin" and affiliation ~= "owner" then
269                         local occupant = self:get_occupant_by_real_jid(to);
270                         if not (occupant and can_see_real_jids(whois, occupant)) then
271                                 is_anonymous = true;
272                         end
273                 end
274         end
275         for occupant_jid, occupant in self:each_occupant() do
276                 if filter == nil or filter(occupant_jid, occupant) then
277                         local x = st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
278                         self:build_item_list(occupant, x, is_anonymous and to_bare ~= occupant.bare_jid); -- can always see your own jids
279                         local pres = st.clone(occupant:get_presence());
280                         pres.attr.to = to;
281                         pres:add_child(x);
282                         self:route_stanza(pres);
283                 end
284         end
285 end
286
287 function room_mt:get_disco_info(stanza)
288         local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#info");
289         local form = dataform.new {
290                 { name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/muc#roominfo" };
291         };
292         module:fire_event("muc-disco#info", {room = self; reply = reply; form = form;});
293         reply:add_child(form:form(nil, "result"));
294         return reply;
295 end
296 module:hook("muc-disco#info", function(event)
297         event.reply:tag("feature", {var = "http://jabber.org/protocol/muc"}):up();
298 end);
299 module:hook("muc-disco#info", function(event)
300         local count = iterators.count(event.room:each_occupant());
301         table.insert(event.form, { name = "muc#roominfo_occupants", label = "Number of occupants", value = tostring(count) });
302 end);
303
304 function room_mt:get_disco_items(stanza)
305         local reply = st.reply(stanza):query("http://jabber.org/protocol/disco#items");
306         for room_jid in self:each_occupant() do
307                 reply:tag("item", {jid = room_jid, name = room_jid:match("/(.*)")}):up();
308         end
309         return reply;
310 end
311
312 function room_mt:handle_kickable(origin, stanza)
313         local real_jid = stanza.attr.from;
314         local occupant = self:get_occupant_by_real_jid(real_jid);
315         if occupant == nil then return nil; end
316         local type, condition, text = stanza:get_error();
317         local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error");
318         if text then
319                 error_message = error_message..": "..text;
320         end
321         occupant:set_session(real_jid, st.presence({type="unavailable"})
322                 :tag('status'):text(error_message));
323         self:save_occupant(occupant);
324         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
325                 :tag("status", {code = "307"})
326         self:publicise_occupant_status(occupant, x);
327         return true;
328 end
329
330 -- Give the room creator owner affiliation
331 module:hook("muc-room-pre-create", function(event)
332         event.room:set_affiliation(true, jid_bare(event.stanza.attr.from), "owner");
333 end, -1);
334
335 -- check if user is banned
336 module:hook("muc-occupant-pre-join", function(event)
337         local room, stanza = event.room, event.stanza;
338         local affiliation = room:get_affiliation(stanza.attr.from);
339         if affiliation == "outcast" then
340                 local reply = st.error_reply(stanza, "auth", "forbidden"):up();
341                 reply.tags[1].attr.code = "403";
342                 event.origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
343                 return true;
344         end
345 end, -10);
346
347 function room_mt:handle_presence_to_occupant(origin, stanza)
348         local type = stanza.attr.type;
349         if type == "error" then -- error, kick em out!
350                 return self:handle_kickable(origin, stanza)
351         elseif type == nil or type == "unavailable" then
352                 local real_jid = stanza.attr.from;
353                 local bare_jid = jid_bare(real_jid);
354                 local orig_occupant, dest_occupant;
355                 local is_new_room = next(self._affiliations) == nil;
356                 if is_new_room then
357                         if type == "unavailable" then return true; end -- Unavailable from someone not in the room
358                         if module:fire_event("muc-room-pre-create", {
359                                         room = self;
360                                         origin = origin;
361                                         stanza = stanza;
362                                 }) then return true; end
363                 else
364                         orig_occupant = self:get_occupant_by_real_jid(real_jid);
365                         if type == "unavailable" and orig_occupant == nil then return true; end -- Unavailable from someone not in the room
366                 end
367                 local is_first_dest_session;
368                 if type == "unavailable" then
369                         -- dest_occupant = nil
370                 elseif orig_occupant and orig_occupant.nick == stanza.attr.to then -- Just a presence update
371                         log("debug", "presence update for %s from session %s", orig_occupant.nick, real_jid);
372                         dest_occupant = orig_occupant;
373                 else
374                         local dest_jid = stanza.attr.to;
375                         dest_occupant = self:get_occupant_by_nick(dest_jid);
376                         if dest_occupant == nil then
377                                 log("debug", "no occupant found for %s; creating new occupant object for %s", dest_jid, real_jid);
378                                 is_first_dest_session = true;
379                                 dest_occupant = self:new_occupant(bare_jid, dest_jid);
380                         else
381                                 is_first_dest_session = false;
382                         end
383                 end
384                 local is_last_orig_session;
385                 if orig_occupant ~= nil then
386                         -- Is there are least 2 sessions?
387                         local iter, ob, last = orig_occupant:each_session();
388                         is_last_orig_session = iter(ob, iter(ob, last)) == nil;
389                 end
390
391                 local event, event_name = {
392                         room = self;
393                         origin = origin;
394                         stanza = stanza;
395                         is_first_session = is_first_dest_session;
396                         is_last_session = is_last_orig_session;
397                 };
398                 if orig_occupant == nil then
399                         event_name = "muc-occupant-pre-join";
400                         event.is_new_room = is_new_room;
401                         event.occupant = dest_occupant;
402                 elseif dest_occupant == nil then
403                         event_name = "muc-occupant-pre-leave";
404                         event.occupant = orig_occupant;
405                 else
406                         event_name = "muc-occupant-pre-change";
407                         event.orig_occupant = orig_occupant;
408                         event.dest_occupant = dest_occupant;
409                 end
410                 if module:fire_event(event_name, event) then return true; end
411
412                 -- Check for nick conflicts
413                 if dest_occupant ~= nil and not is_first_dest_session and bare_jid ~= jid_bare(dest_occupant.bare_jid) then -- new nick or has different bare real jid
414                         log("debug", "%s couldn't join due to nick conflict: %s", real_jid, dest_occupant.nick);
415                         local reply = st.error_reply(stanza, "cancel", "conflict"):up();
416                         reply.tags[1].attr.code = "409";
417                         origin.send(reply:tag("x", {xmlns = "http://jabber.org/protocol/muc"}));
418                         return true;
419                 end
420
421                 -- Send presence stanza about original occupant
422                 if orig_occupant ~= nil and orig_occupant ~= dest_occupant then
423                         local orig_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
424                         local dest_nick;
425                         if dest_occupant == nil then -- Session is leaving
426                                 log("debug", "session %s is leaving occupant %s", real_jid, orig_occupant.nick);
427                                 if is_last_orig_session then
428                                         orig_occupant.role = nil;
429                                 end
430                                 orig_occupant:set_session(real_jid, stanza);
431                         else
432                                 log("debug", "session %s is changing from occupant %s to %s", real_jid, orig_occupant.nick, dest_occupant.nick);
433                                 local generated_unavail = st.presence {from = orig_occupant.nick, to = real_jid, type = "unavailable"};
434                                 orig_occupant:set_session(real_jid, generated_unavail);
435                                 dest_nick = select(3, jid_split(dest_occupant.nick));
436                                 if not is_first_dest_session then -- User is swapping into another pre-existing session
437                                         log("debug", "session %s is swapping into multisession %s, showing it leave.", real_jid, dest_occupant.nick);
438                                         -- Show the other session leaving
439                                         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";})
440                                                 :tag("status"):text("you are joining pre-existing session " .. dest_nick):up();
441                                         add_item(x, self:get_affiliation(bare_jid), "none");
442                                         local pr = st.presence{from = dest_occupant.nick, to = real_jid, type = "unavailable"}
443                                                 :add_child(x);
444                                         self:route_stanza(pr);
445                                 end
446                                 if is_first_dest_session and is_last_orig_session then -- Normal nick change
447                                         log("debug", "no sessions in %s left; publically marking as nick change", orig_occupant.nick);
448                                         orig_x:tag("status", {code = "303";}):up();
449                                 else -- The session itself always needs to see a nick change
450                                         -- don't want to get our old nick's available presence,
451                                         -- so remove our session from there, and manually generate an unavailable
452                                         orig_occupant:remove_session(real_jid);
453                                         log("debug", "generating nick change for %s", real_jid);
454                                         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
455                                         -- self:build_item_list(orig_occupant, x, false, dest_nick); -- COMPAT: clients get confused if they see other items besides their own
456                                         add_item(x, self:get_affiliation(bare_jid), orig_occupant.role, real_jid, dest_nick);
457                                         x:tag("status", {code = "303";}):up();
458                                         x:tag("status", {code = "110";}):up();
459                                         self:route_stanza(generated_unavail:add_child(x));
460                                         dest_nick = nil; -- set dest_nick to nil; so general populance doesn't see it for whole orig_occupant
461                                 end
462                         end
463                         self:save_occupant(orig_occupant);
464                         self:publicise_occupant_status(orig_occupant, orig_x, dest_nick);
465
466                         if is_last_orig_session then
467                                 module:fire_event("muc-occupant-left", {room = self; nick = orig_occupant.nick; occupant = orig_occupant;});
468                         end
469                 end
470
471                 if dest_occupant ~= nil then
472                         dest_occupant:set_session(real_jid, stanza);
473                         local dest_x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
474                         if is_new_room then
475                                 dest_x:tag("status", {code = "201"}):up();
476                         end
477                         if orig_occupant == nil and self:get_whois() == "anyone" then
478                                 dest_x:tag("status", {code = "100"}):up();
479                         end
480                         self:save_occupant(dest_occupant);
481
482                         if orig_occupant == nil then
483                                 -- Send occupant list to newly joined user
484                                 self:send_occupant_list(real_jid, function(nick, occupant)
485                                         -- Don't include self
486                                         return occupant:get_presence(real_jid) == nil;
487                                 end)
488                         end
489                         self:publicise_occupant_status(dest_occupant, dest_x);
490
491                         if orig_occupant ~= nil and orig_occupant ~= dest_occupant and not is_last_orig_session then -- If user is swapping and wasn't last original session
492                                 log("debug", "session %s split nicks; showing %s rejoining", real_jid, orig_occupant.nick);
493                                 -- Show the original nick joining again
494                                 local pr = st.clone(orig_occupant:get_presence());
495                                 pr.attr.to = real_jid;
496                                 local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user";});
497                                 self:build_item_list(orig_occupant, x, false);
498                                 -- TODO: new status code to inform client this was the multi-session it left?
499                                 pr:add_child(x);
500                                 self:route_stanza(pr);
501                         end
502
503                         if orig_occupant == nil then
504                                 if is_first_dest_session then
505                                         module:fire_event("muc-occupant-joined", {room = self; nick = dest_occupant.nick; occupant = dest_occupant;});
506                                 end
507                                 module:fire_event("muc-occupant-session-new", {room = self; nick = dest_occupant.nick; occupant = dest_occupant; stanza = stanza; jid = real_jid;});
508                         end
509                 end
510         elseif type ~= 'result' then -- bad type
511                 if type ~= 'visible' and type ~= 'invisible' then -- COMPAT ejabberd can broadcast or forward XEP-0018 presences
512                         origin.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME correct error?
513                 end
514         end
515         return true;
516 end
517
518 function room_mt:handle_iq_to_occupant(origin, stanza)
519         local from, to = stanza.attr.from, stanza.attr.to;
520         local type = stanza.attr.type;
521         local id = stanza.attr.id;
522         local occupant = self:get_occupant_by_nick(to);
523         if (type == "error" or type == "result") then
524                 do -- deconstruct_stanza_id
525                         if not occupant then return nil; end
526                         local from_jid, id, to_jid_hash = (base64.decode(stanza.attr.id) or ""):match("^(.+)%z(.*)%z(.+)$");
527                         if not(from == from_jid or from == jid_bare(from_jid)) then return nil; end
528                         local from_occupant_jid = self:get_occupant_jid(from_jid);
529                         if from_occupant_jid == nil then return nil; end
530                         local session_jid
531                         for to_jid in occupant:each_session() do
532                                 if md5(to_jid) == to_jid_hash then
533                                         session_jid = to_jid;
534                                         break;
535                                 end
536                         end
537                         if session_jid == nil then return nil; end
538                         stanza.attr.from, stanza.attr.to, stanza.attr.id = from_occupant_jid, session_jid, id;
539                 end
540                 log("debug", "%s sent private iq stanza to %s (%s)", from, to, stanza.attr.to);
541                 self:route_stanza(stanza);
542                 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
543                 return true;
544         else -- Type is "get" or "set"
545                 local current_nick = self:get_occupant_jid(from);
546                 if not current_nick then
547                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
548                         return true;
549                 end
550                 if not occupant then -- recipient not in room
551                         origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
552                         return true;
553                 end
554                 do -- construct_stanza_id
555                         stanza.attr.id = base64.encode(occupant.jid.."\0"..stanza.attr.id.."\0"..md5(from));
556                 end
557                 stanza.attr.from, stanza.attr.to = current_nick, occupant.jid;
558                 log("debug", "%s sent private iq stanza to %s (%s)", from, to, occupant.jid);
559                 if stanza.tags[1].attr.xmlns == 'vcard-temp' then
560                         stanza.attr.to = jid_bare(stanza.attr.to);
561                 end
562                 self:route_stanza(stanza);
563                 stanza.attr.from, stanza.attr.to, stanza.attr.id = from, to, id;
564                 return true;
565         end
566 end
567
568 function room_mt:handle_message_to_occupant(origin, stanza)
569         local from, to = stanza.attr.from, stanza.attr.to;
570         local current_nick = self:get_occupant_jid(from);
571         local type = stanza.attr.type;
572         if not current_nick then -- not in room
573                 if type ~= "error" then
574                         origin.send(st.error_reply(stanza, "cancel", "not-acceptable"));
575                 end
576                 return true;
577         end
578         if type == "groupchat" then -- groupchat messages not allowed in PM
579                 origin.send(st.error_reply(stanza, "modify", "bad-request"));
580                 return true;
581         elseif type == "error" and is_kickable_error(stanza) then
582                 log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid);
583                 return self:handle_kickable(origin, stanza); -- send unavailable
584         end
585
586         local o_data = self:get_occupant_by_nick(to);
587         if not o_data then
588                 origin.send(st.error_reply(stanza, "cancel", "item-not-found", "Recipient not in room"));
589                 return true;
590         end
591         log("debug", "%s sent private message stanza to %s (%s)", from, to, o_data.jid);
592         stanza:tag("x", { xmlns = "http://jabber.org/protocol/muc#user" }):up();
593         stanza.attr.from = current_nick;
594         self:route_to_occupant(o_data, stanza)
595         -- TODO: Remove x tag?
596         stanza.attr.from = from;
597         return true;
598 end
599
600 function room_mt:send_form(origin, stanza)
601         origin.send(st.reply(stanza):query("http://jabber.org/protocol/muc#owner")
602                 :add_child(self:get_form_layout(stanza.attr.from):form())
603         );
604 end
605
606 function room_mt:get_form_layout(actor)
607         local form = dataform.new({
608                 title = "Configuration for "..self.jid,
609                 instructions = "Complete and submit this form to configure the room.",
610                 {
611                         name = 'FORM_TYPE',
612                         type = 'hidden',
613                         value = 'http://jabber.org/protocol/muc#roomconfig'
614                 }
615         });
616         return module:fire_event("muc-config-form", { room = self, actor = actor, form = form }) or form;
617 end
618
619 function room_mt:process_form(origin, stanza)
620         local form = stanza.tags[1]:get_child("x", "jabber:x:data");
621         if form.attr.type == "cancel" then
622                 origin.send(st.reply(stanza));
623         elseif form.attr.type == "submit" then
624                 local fields;
625                 if form.tags[1] == nil then -- Instant room
626                         fields = {};
627                 else
628                         fields = self:get_form_layout(stanza.attr.from):data(form);
629                         if fields.FORM_TYPE ~= "http://jabber.org/protocol/muc#roomconfig" then
630                                 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Form is not of type room configuration"));
631                                 return true;
632                         end
633                 end
634
635                 local event = {room = self; origin = origin; stanza = stanza; fields = fields; status_codes = {};};
636                 function event.update_option(name, field, allowed)
637                         local new = fields[field];
638                         if new == nil then return; end
639                         if allowed and not allowed[new] then return; end
640                         if new == self["get_"..name](self) then return; end
641                         event.status_codes["104"] = true;
642                         self["set_"..name](self, new);
643                         return true;
644                 end
645                 module:fire_event("muc-config-submitted", event);
646
647                 if self.save then self:save(true); end
648                 origin.send(st.reply(stanza));
649
650                 if next(event.status_codes) then
651                         local msg = st.message({type='groupchat', from=self.jid})
652                                 :tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
653                         for code in pairs(event.status_codes) do
654                                 msg:tag("status", {code = code;}):up();
655                         end
656                         msg:up();
657                         self:broadcast_message(msg);
658                 end
659         else
660                 origin.send(st.error_reply(stanza, "cancel", "bad-request", "Not a submitted form"));
661         end
662         return true;
663 end
664
665 -- Removes everyone from the room
666 function room_mt:clear(x)
667         x = x or st.stanza("x", {xmlns='http://jabber.org/protocol/muc#user'});
668         local occupants_updated = {};
669         for nick, occupant in self:each_occupant() do
670                 occupant.role = nil;
671                 self:save_occupant(occupant);
672                 occupants_updated[occupant] = true;
673         end
674         for occupant in pairs(occupants_updated) do
675                 self:publicise_occupant_status(occupant, x);
676                 module:fire_event("muc-occupant-left", { room = self; nick = occupant.nick; occupant = occupant;});
677         end
678 end
679
680 function room_mt:destroy(newjid, reason, password)
681         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"})
682                 :tag("item", { affiliation='none', role='none' }):up()
683                 :tag("destroy", {jid=newjid});
684         if reason then x:tag("reason"):text(reason):up(); end
685         if password then x:tag("password"):text(password):up(); end
686         x:up();
687         self:clear(x);
688         module:fire_event("muc-room-destroyed", { room = self });
689 end
690
691 function room_mt:handle_disco_info_get_query(origin, stanza)
692         origin.send(self:get_disco_info(stanza));
693         return true;
694 end
695
696 function room_mt:handle_disco_items_get_query(origin, stanza)
697         origin.send(self:get_disco_items(stanza));
698         return true;
699 end
700
701 function room_mt:handle_admin_query_set_command(origin, stanza)
702         local item = stanza.tags[1].tags[1];
703         if item.attr.jid then -- Validate provided JID
704                 item.attr.jid = jid_prep(item.attr.jid);
705                 if not item.attr.jid then
706                         origin.send(st.error_reply(stanza, "modify", "jid-malformed"));
707                         return true;
708                 end
709         end
710         if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation
711                 local occupant = self:get_occupant_by_nick(self.jid.."/"..item.attr.nick);
712                 if occupant then item.attr.jid = occupant.jid; end
713         elseif not item.attr.nick and item.attr.jid then
714                 local nick = self:get_occupant_jid(item.attr.jid);
715                 if nick then item.attr.nick = select(3, jid_split(nick)); end
716         end
717         local actor = stanza.attr.from;
718         local reason = item:get_child_text("reason");
719         local success, errtype, err
720         if item.attr.affiliation and item.attr.jid and not item.attr.role then
721                 success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, reason);
722         elseif item.attr.role and item.attr.nick and not item.attr.affiliation then
723                 success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, reason);
724         else
725                 success, errtype, err = nil, "cancel", "bad-request";
726         end
727         if not success then origin.send(st.error_reply(stanza, errtype, err)); end
728         origin.send(st.reply(stanza));
729         return true;
730 end
731
732 function room_mt:handle_admin_query_get_command(origin, stanza)
733         local actor = stanza.attr.from;
734         local affiliation = self:get_affiliation(actor);
735         local item = stanza.tags[1].tags[1];
736         local _aff = item.attr.affiliation;
737         local _rol = item.attr.role;
738         if _aff and not _rol then
739                 if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then
740                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
741                         for jid, affiliation in pairs(self._affiliations) do
742                                 if affiliation == _aff then
743                                         reply:tag("item", {affiliation = _aff, jid = jid}):up();
744                                 end
745                         end
746                         origin.send(reply);
747                         return true;
748                 else
749                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
750                         return true;
751                 end
752         elseif _rol and not _aff then
753                 local role = self:get_role(self:get_occupant_jid(actor)) or self:get_default_role(affiliation);
754                 if valid_roles[role or "none"] >= valid_roles.moderator then
755                         if _rol == "none" then _rol = nil; end
756                         local reply = st.reply(stanza):query("http://jabber.org/protocol/muc#admin");
757                         -- TODO: whois check here? (though fully anonymous rooms are not supported)
758                         for occupant_jid, occupant in self:each_occupant() do
759                                 if occupant.role == _rol then
760                                         local nick = select(3,jid_split(occupant_jid));
761                                         self:build_item_list(occupant, reply, false, nick);
762                                 end
763                         end
764                         origin.send(reply:up());
765                         return true;
766                 else
767                         origin.send(st.error_reply(stanza, "auth", "forbidden"));
768                         return true;
769                 end
770         else
771                 origin.send(st.error_reply(stanza, "cancel", "bad-request"));
772                 return true;
773         end
774 end
775
776 function room_mt:handle_owner_query_get_to_room(origin, stanza)
777         if self:get_affiliation(stanza.attr.from) ~= "owner" then
778                 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
779                 return true;
780         end
781
782         self:send_form(origin, stanza);
783         return true;
784 end
785 function room_mt:handle_owner_query_set_to_room(origin, stanza)
786         if self:get_affiliation(stanza.attr.from) ~= "owner" then
787                 origin.send(st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"));
788                 return true;
789         end
790
791         local child = stanza.tags[1].tags[1];
792         if not child then
793                 origin.send(st.error_reply(stanza, "modify", "bad-request"));
794                 return true;
795         elseif child.name == "destroy" then
796                 local newjid = child.attr.jid;
797                 local reason = child:get_child_text("reason");
798                 local password = child:get_child_text("password");
799                 self:destroy(newjid, reason, password);
800                 origin.send(st.reply(stanza));
801                 return true;
802         elseif child.name == "x" and child.attr.xmlns == "jabber:x:data" then
803                 return self:process_form(origin, stanza);
804         else
805                 origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
806                 return true;
807         end
808 end
809
810 function room_mt:handle_groupchat_to_room(origin, stanza)
811         local from = stanza.attr.from;
812         local occupant = self:get_occupant_by_real_jid(from);
813         if module:fire_event("muc-occupant-groupchat", {
814                 room = self; origin = origin; stanza = stanza; from = from; occupant = occupant;
815         }) then return true; end
816         stanza.attr.from = occupant.nick;
817         self:broadcast_message(stanza);
818         stanza.attr.from = from;
819         return true;
820 end
821
822 -- Role check
823 module:hook("muc-occupant-groupchat", function(event)
824         local role_rank = valid_roles[event.occupant and event.occupant.role or "none"];
825         if role_rank <= valid_roles.none then
826                 event.origin.send(st.error_reply(event.stanza, "cancel", "not-acceptable"));
827                 return true;
828         elseif role_rank <= valid_roles.visitor then
829                 event.origin.send(st.error_reply(event.stanza, "auth", "forbidden"));
830                 return true;
831         end
832 end, 50);
833
834 -- hack - some buggy clients send presence updates to the room rather than their nick
835 function room_mt:handle_presence_to_room(origin, stanza)
836         local current_nick = self:get_occupant_jid(stanza.attr.from);
837         local handled
838         if current_nick then
839                 local to = stanza.attr.to;
840                 stanza.attr.to = current_nick;
841                 handled = self:handle_presence_to_occupant(origin, stanza);
842                 stanza.attr.to = to;
843         end
844         return handled;
845 end
846
847 -- Need visitor role or higher to invite
848 module:hook("muc-pre-invite", function(event)
849         local room, stanza = event.room, event.stanza;
850         local _from, _to = stanza.attr.from, stanza.attr.to;
851         local inviter = room:get_occupant_by_real_jid(_from);
852         local role = inviter and inviter.role or room:get_default_role(room:get_affiliation(_from));
853         if valid_roles[role or "none"] <= valid_roles.visitor then
854                 event.origin.send(st.error_reply(stanza, "auth", "forbidden"));
855                 return true;
856         end
857 end);
858
859 function room_mt:handle_mediated_invite(origin, stanza)
860         local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
861         local invitee = jid_prep(payload.attr.to);
862         if not invitee then
863                 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
864                 return true;
865         elseif module:fire_event("muc-pre-invite", {room = self, origin = origin, stanza = stanza}) then
866                 return true;
867         end
868         local invite = muc_util.filter_muc_x(st.clone(stanza));
869         invite.attr.from = self.jid;
870         invite.attr.to = invitee;
871         invite:tag('x', {xmlns='http://jabber.org/protocol/muc#user'})
872                         :tag('invite', {from = stanza.attr.from;})
873                                 :tag('reason'):text(payload:get_child_text("reason")):up()
874                         :up()
875                 :up();
876         if not module:fire_event("muc-invite", {room = self, stanza = invite, origin = origin, incoming = stanza}) then
877                 self:route_stanza(invite);
878         end
879         return true;
880 end
881
882 -- COMPAT: Some older clients expect this
883 module:hook("muc-invite", function(event)
884         local room, stanza = event.room, event.stanza;
885         local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
886         local reason = invite:get_child_text("reason");
887         stanza:tag('x', {xmlns = "jabber:x:conference"; jid = room.jid;})
888                 :text(reason or "")
889         :up();
890 end);
891
892 -- Add a plain message for clients which don't support invites
893 module:hook("muc-invite", function(event)
894         local room, stanza = event.room, event.stanza;
895         if not stanza:get_child("body") then
896                 local invite = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("invite");
897                 local reason = invite:get_child_text("reason") or "";
898                 stanza:tag("body")
899                         :text(invite.attr.from.." invited you to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
900                 :up();
901         end
902 end);
903
904 function room_mt:handle_mediated_decline(origin, stanza)
905         local payload = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
906         local declinee = jid_prep(payload.attr.to);
907         if not declinee then
908                 origin.send(st.error_reply(stanza, "cancel", "jid-malformed"));
909                 return true;
910         elseif module:fire_event("muc-pre-decline", {room = self, origin = origin, stanza = stanza}) then
911                 return true;
912         end
913         local decline = muc_util.filter_muc_x(st.clone(stanza));
914         decline.attr.from = self.jid;
915         decline.attr.to = declinee;
916         decline:tag("x", {xmlns = "http://jabber.org/protocol/muc#user"})
917                         :tag("decline", {from = stanza.attr.from})
918                                 :tag("reason"):text(payload:get_child_text("reason")):up()
919                         :up()
920                 :up();
921         if not module:fire_event("muc-decline", {room = self, stanza = decline, origin = origin, incoming = stanza}) then
922                 local declinee = decline.attr.to; -- re-fetch, in case event modified it
923                 local occupant
924                 if jid_bare(declinee) == self.jid then -- declinee jid is already an in-room jid
925                         occupant = self:get_occupant_by_nick(declinee);
926                 end
927                 if occupant then
928                         self:route_to_occupant(occupant, decline);
929                 else
930                         self:route_stanza(decline);
931                 end
932         end
933         return true;
934 end
935
936 -- Add a plain message for clients which don't support declines
937 module:hook("muc-decline", function(event)
938         local room, stanza = event.room, event.stanza;
939         if not stanza:get_child("body") then
940                 local decline = stanza:get_child("x", "http://jabber.org/protocol/muc#user"):get_child("decline");
941                 local reason = decline:get_child_text("reason") or "";
942                 stanza:tag("body")
943                         :text(decline.attr.from.." declined your invite to the room "..room.jid..(reason == "" and (" ("..reason..")") or ""))
944                 :up();
945         end
946 end);
947
948 function room_mt:handle_message_to_room(origin, stanza)
949         local type = stanza.attr.type;
950         if type == "groupchat" then
951                 return self:handle_groupchat_to_room(origin, stanza)
952         elseif type == "error" and is_kickable_error(stanza) then
953                 return self:handle_kickable(origin, stanza)
954         elseif type == nil then
955                 local x = stanza:get_child("x", "http://jabber.org/protocol/muc#user");
956                 if x then
957                         local payload = x.tags[1];
958                         if payload == nil then
959                                 -- fallthrough
960                         elseif payload.name == "invite" and payload.attr.to then
961                                 return self:handle_mediated_invite(origin, stanza)
962                         elseif payload.name == "decline" and payload.attr.to then
963                                 return self:handle_mediated_decline(origin, stanza)
964                         end
965                         origin.send(st.error_reply(stanza, "cancel", "bad-request"));
966                         return true;
967                 end
968         end
969 end
970
971 function room_mt:route_stanza(stanza)
972         module:send(stanza);
973 end
974
975 function room_mt:get_affiliation(jid)
976         local node, host, resource = jid_split(jid);
977         local bare = node and node.."@"..host or host;
978         local result = self._affiliations[bare]; -- Affiliations are granted, revoked, and maintained based on the user's bare JID.
979         if not result and self._affiliations[host] == "outcast" then result = "outcast"; end -- host banned
980         return result;
981 end
982
983 function room_mt:set_affiliation(actor, jid, affiliation, reason)
984         if not actor then return nil, "modify", "not-acceptable"; end;
985
986         jid = jid_bare(jid);
987
988         if valid_affiliations[affiliation or "none"] == nil then
989                 return nil, "modify", "not-acceptable";
990         end
991         affiliation = affiliation ~= "none" and affiliation or nil; -- coerces `affiliation == false` to `nil`
992
993         local target_affiliation = self._affiliations[jid]; -- Raw; don't want to check against host
994         local is_downgrade = valid_affiliations[target_affiliation or "none"] > valid_affiliations[affiliation or "none"];
995
996         if actor ~= true then
997                 local actor_affiliation = self:get_affiliation(actor);
998                 if actor_affiliation == "owner" then
999                         if jid_bare(actor) == jid then -- self change
1000                                 -- need at least one owner
1001                                 local is_last = true;
1002                                 for j, aff in pairs(self._affiliations) do if j ~= jid and aff == "owner" then is_last = false; break; end end
1003                                 if is_last then
1004                                         return nil, "cancel", "conflict";
1005                                 end
1006                         end
1007                         -- owners can do anything else
1008                 elseif affiliation == "owner" or affiliation == "admin"
1009                         or actor_affiliation ~= "admin"
1010                         or target_affiliation == "owner" or target_affiliation == "admin" then
1011                         -- Can't demote owners or other admins
1012                         return nil, "cancel", "not-allowed";
1013                 end
1014         end
1015
1016         -- Set in 'database'
1017         self._affiliations[jid] = affiliation;
1018
1019         -- Update roles
1020         local role = self:get_default_role(affiliation);
1021         local role_rank = valid_roles[role or "none"];
1022         local occupants_updated = {}; -- Filled with old roles
1023         for nick, occupant in self:each_occupant() do
1024                 if occupant.bare_jid == jid then
1025                         -- need to publcize in all cases; as affiliation in <item/> has changed.
1026                         occupants_updated[occupant] = occupant.role;
1027                         if occupant.role ~= role and (
1028                                 is_downgrade or
1029                                 valid_roles[occupant.role or "none"] < role_rank -- upgrade
1030                         ) then
1031                                 occupant.role = role;
1032                                 self:save_occupant(occupant);
1033                         end
1034                 end
1035         end
1036
1037         -- Tell the room of the new occupant affiliations+roles
1038         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1039         if not role then -- getting kicked
1040                 if affiliation == "outcast" then
1041                         x:tag("status", {code="301"}):up(); -- banned
1042                 else
1043                         x:tag("status", {code="321"}):up(); -- affiliation change
1044                 end
1045         end
1046         local is_semi_anonymous = self:get_whois() == "moderators";
1047         for occupant, old_role in pairs(occupants_updated) do
1048                 self:publicise_occupant_status(occupant, x, nil, actor, reason);
1049                 if is_semi_anonymous and
1050                         (old_role == "moderator" and occupant.role ~= "moderator") or
1051                         (old_role ~= "moderator" and occupant.role == "moderator") then -- Has gained or lost moderator status
1052                         -- Send everyone else's presences (as jid visibility has changed)
1053                         for real_jid in occupant:each_session() do
1054                                 self:send_occupant_list(real_jid, function(occupant_jid, occupant)
1055                                         return occupant.bare_jid ~= jid;
1056                                 end);
1057                         end
1058                 end
1059         end
1060
1061         if self.save then self:save(); end
1062
1063         module:fire_event("muc-set-affiliation", {
1064                 room = self;
1065                 actor = actor;
1066                 jid = jid;
1067                 affiliation = affiliation or "none";
1068                 reason = reason;
1069                 previous_affiliation = target_affiliation;
1070                 in_room = next(occupants_updated) ~= nil;
1071         });
1072
1073         return true;
1074 end
1075
1076 function room_mt:get_role(nick)
1077         local occupant = self:get_occupant_by_nick(nick);
1078         return occupant and occupant.role or nil;
1079 end
1080
1081 function room_mt:set_role(actor, occupant_jid, role, reason)
1082         if not actor then return nil, "modify", "not-acceptable"; end
1083
1084         local occupant = self:get_occupant_by_nick(occupant_jid);
1085         if not occupant then return nil, "modify", "not-acceptable"; end
1086
1087         if valid_roles[role or "none"] == nil then
1088                 return nil, "modify", "not-acceptable";
1089         end
1090         role = role ~= "none" and role or nil; -- coerces `role == false` to `nil`
1091
1092         if actor ~= true then
1093                 -- Can't do anything to other owners or admins
1094                 local occupant_affiliation = self:get_affiliation(occupant.bare_jid);
1095                 if occupant_affiliation == "owner" and occupant_affiliation == "admin" then
1096                         return nil, "cancel", "not-allowed";
1097                 end
1098
1099                 -- If you are trying to give or take moderator role you need to be an owner or admin
1100                 if occupant.role == "moderator" or role == "moderator" then
1101                         local actor_affiliation = self:get_affiliation(actor);
1102                         if actor_affiliation ~= "owner" and actor_affiliation ~= "admin" then
1103                                 return nil, "cancel", "not-allowed";
1104                         end
1105                 end
1106
1107                 -- Need to be in the room and a moderator
1108                 local actor_occupant = self:get_occupant_by_real_jid(actor);
1109                 if not actor_occupant or actor_occupant.role ~= "moderator" then
1110                         return nil, "cancel", "not-allowed";
1111                 end
1112         end
1113
1114         local x = st.stanza("x", {xmlns = "http://jabber.org/protocol/muc#user"});
1115         if not role then
1116                 x:tag("status", {code = "307"}):up();
1117         end
1118         occupant.role = role;
1119         self:save_occupant(occupant);
1120         self:publicise_occupant_status(occupant, x, nil, actor, reason);
1121         return true;
1122 end
1123
1124 local affiliation_notify = module:require "muc/affiliation_notify";
1125
1126 local name = module:require "muc/name";
1127 room_mt.get_name = name.get;
1128 room_mt.set_name = name.set;
1129
1130 local description = module:require "muc/description";
1131 room_mt.get_description = description.get;
1132 room_mt.set_description = description.set;
1133
1134 local hidden = module:require "muc/hidden";
1135 room_mt.get_hidden = hidden.get;
1136 room_mt.set_hidden = hidden.set;
1137 function room_mt:get_public()
1138         return not self:get_hidden();
1139 end
1140 function room_mt:set_public(public)
1141         return self:set_hidden(not public);
1142 end
1143
1144 local password = module:require "muc/password";
1145 room_mt.get_password = password.get;
1146 room_mt.set_password = password.set;
1147
1148 local whois = module:require "muc/whois";
1149 room_mt.get_whois = whois.get;
1150 room_mt.set_whois = whois.set;
1151
1152 local members_only = module:require "muc/members_only";
1153 room_mt.get_members_only = members_only.get;
1154 room_mt.set_members_only = members_only.set;
1155
1156 local moderated = module:require "muc/moderated";
1157 room_mt.get_moderated = moderated.get;
1158 room_mt.set_moderated = moderated.set;
1159
1160 local persistent = module:require "muc/persistent";
1161 room_mt.get_persistent = persistent.get;
1162 room_mt.set_persistent = persistent.set;
1163
1164 local subject = module:require "muc/subject";
1165 room_mt.get_changesubject = subject.get_changesubject;
1166 room_mt.set_changesubject = subject.set_changesubject;
1167 room_mt.get_subject = subject.get;
1168 room_mt.set_subject = subject.set;
1169 room_mt.send_subject = subject.send;
1170
1171 local history = module:require "muc/history";
1172 room_mt.send_history = history.send;
1173 room_mt.get_historylength = history.get_length;
1174 room_mt.set_historylength = history.set_length;
1175
1176 local _M = {}; -- module "muc"
1177
1178 function _M.new_room(jid, config)
1179         return setmetatable({
1180                 jid = jid;
1181                 _jid_nick = {};
1182                 _occupants = {};
1183                 _data = {
1184                 };
1185                 _affiliations = {};
1186         }, room_mt);
1187 end
1188
1189 _M.room_mt = room_mt;
1190
1191 return _M;