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