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