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