MUCRoomImpl.java 65.9 KB
Newer Older
Matt Tucker's avatar
Matt Tucker committed
1 2 3 4 5
/**
 * $RCSfile$
 * $Revision$
 * $Date$
 *
Matt Tucker's avatar
Matt Tucker committed
6
 * Copyright (C) 2004 Jive Software. All rights reserved.
Matt Tucker's avatar
Matt Tucker committed
7
 *
Matt Tucker's avatar
Matt Tucker committed
8 9
 * This software is published under the terms of the GNU Public License (GPL),
 * a copy of which is included in this distribution.
Matt Tucker's avatar
Matt Tucker committed
10 11 12 13 14 15
 */

package org.jivesoftware.messenger.muc.spi;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
16
import java.util.concurrent.CopyOnWriteArrayList;
Matt Tucker's avatar
Matt Tucker committed
17 18 19 20 21 22 23 24 25 26
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

import org.jivesoftware.database.SequenceManager;
import org.jivesoftware.messenger.muc.*;
import org.jivesoftware.util.*;
import org.jivesoftware.messenger.*;
import org.jivesoftware.messenger.auth.UnauthorizedException;
import org.jivesoftware.messenger.user.UserAlreadyExistsException;
import org.jivesoftware.messenger.user.UserNotFoundException;
27 28
import org.xmpp.packet.*;
import org.dom4j.Element;
Matt Tucker's avatar
Matt Tucker committed
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56

/**
 * Simple in-memory implementation of a chatroom. A MUCRoomImpl could represent a persistent room 
 * which means that its configuration will be maintained in synch with its representation in the 
 * database.
 * 
 * @author Gaston Dombiak
 */
public class MUCRoomImpl implements MUCRoom {

    /**
     * The server hosting the room.
     */
    private MultiUserChatServer server;

    /**
     * The occupants of the room accessible by the occupants nickname.
     */
    private Map<String,MUCRole> occupants = new ConcurrentHashMap<String, MUCRole>();

    /**
     * The occupants of the room accessible by the occupants bare JID.
     */
    private Map<String, List<MUCRole>> occupantsByBareJID = new ConcurrentHashMap<String, List<MUCRole>>();

    /**
     * The occupants of the room accessible by the occupants full JID.
     */
57
    private Map<JID, MUCRole> occupantsByFullJID = new ConcurrentHashMap<JID, MUCRole>();
Matt Tucker's avatar
Matt Tucker committed
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88

    /**
     * The name of the room.
     */
    private String name;

    /**
     * A lock to protect the room occupants.
     */
    ReadWriteLock lock = new ReentrantReadWriteLock();

    /**
     * The role of the room itself.
     */
    private MUCRole role;

    /**
     * The router used to send packets for the room.
     */
    private PacketRouter router;

    /**
     * The start time of the chat.
     */
    long startTime;

    /**
     * The end time of the chat.
     */
    long endTime;

89 90 91 92 93 94 95 96
    /**
     * After a room has been destroyed it may remain in memory but it won't be possible to use it.
     * When a room is destroyed it is immediately removed from the MultiUserChatServer but it's
     * possible that while the room was being destroyed it was being used by another thread so we
     * need to protect the room under these rare circumstances.
     */
    boolean isDestroyed = false;

Matt Tucker's avatar
Matt Tucker committed
97 98 99 100 101 102
    /**
     * ChatRoomHistory object.
     */
    private MUCRoomHistory roomHistory;

    /**
103
     * Time when the room was locked. A value of zero means that the room is unlocked.
Matt Tucker's avatar
Matt Tucker committed
104
     */
105
    private long lockedTime;
Matt Tucker's avatar
Matt Tucker committed
106 107 108 109

    /**
     * List of chatroom's owner. The list contains only bare jid.
     */
110
    List<String> owners = new CopyOnWriteArrayList<String>();
Matt Tucker's avatar
Matt Tucker committed
111 112 113 114

    /**
     * List of chatroom's admin. The list contains only bare jid.
     */
115
    List<String> admins = new CopyOnWriteArrayList<String>();
Matt Tucker's avatar
Matt Tucker committed
116 117 118 119 120 121 122 123 124

    /**
     * List of chatroom's members. The list contains only bare jid.
     */
    private Map<String, String> members = new ConcurrentHashMap<String,String>();

    /**
     * List of chatroom's outcast. The list contains only bare jid of not allowed users.
     */
125
    private List<String> outcasts = new CopyOnWriteArrayList<String>();
Matt Tucker's avatar
Matt Tucker committed
126

127 128 129 130 131
    /**
     * The natural language name of the room.
     */
    private String naturalLanguageName;

Matt Tucker's avatar
Matt Tucker committed
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
    /**
     * Description of the room. The owner can change the description using the room configuration
     * form.
     */
    private String description;

    /**
     * Indicates if occupants are allowed to change the subject of the room. 
     */
    private boolean canOccupantsChangeSubject = false;

    /**
     * Maximum number of occupants that could be present in the room. If the limit's been reached
     * and a user tries to join, a not-allowed error will be returned.
     */
    private int maxUsers = 30;

    /**
     * List of roles of which presence will be broadcasted to the rest of the occupants. This
     * feature is useful for implementing "invisible" occupants.
     */
153
    private List<String> rolesToBroadcastPresence = new ArrayList<String>();
Matt Tucker's avatar
Matt Tucker committed
154 155 156 157 158 159 160 161

    /**
     * A public room means that the room is searchable and visible. This means that the room can be
     * located using disco requests.
     */
    private boolean publicRoom = true;

    /**
162 163
     * Persistent rooms are saved to the database to make sure that rooms configurations can be
     * restored in case the server goes down.
Matt Tucker's avatar
Matt Tucker committed
164 165 166 167 168 169 170 171 172 173 174 175 176 177
     */
    private boolean persistent = false;

    /**
     * Moderated rooms enable only participants to speak. Users that join the room and aren't
     * participants can't speak (they are just visitors).
     */
    private boolean moderated = false;

    /**
     * A room is considered members-only if an invitation is required in order to enter the room.
     * Any user that is not a member of the room won't be able to join the room unless the user
     * decides to register with the room (thus becoming a member).
     */
178
    private boolean membersOnly = false;
Matt Tucker's avatar
Matt Tucker committed
179 180 181 182 183 184 185 186 187 188

    /**
     * Some rooms may restrict the occupants that are able to send invitations. Sending an 
     * invitation in a members-only room adds the invitee to the members list.
     */
    private boolean canOccupantsInvite = false;

    /**
     * The password that every occupant should provide in order to enter the room.
     */
189
    private String password = null;
Matt Tucker's avatar
Matt Tucker committed
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224

    /**
     * Every presence packet can include the JID of every occupant unless the owner deactives this
     * configuration. 
     */
    private boolean canAnyoneDiscoverJID = false;

    /**
     * Enables the logging of the conversation. The conversation in the room will be saved to the
     * database.
     */
    private boolean logEnabled = false;

    /**
     * Internal component that handles IQ packets sent by the room owners.
     */
    private IQOwnerHandler iqOwnerHandler;

    /**
     * Internal component that handles IQ packets sent by moderators, admins and owners.
     */
    private IQAdminHandler iqAdminHandler;

    /**
     * The last known subject of the room. This information is used to respond disco requests. The
     * MUCRoomHistory class holds the history of the room together with the last message that set
     * the room's subject.
     */
    private String subject = "";
    
    /**
     * The ID of the room. If the room is temporary and does not log its conversation then the value
     * will always be -1. Otherwise a value will be obtained from the database.
     */
    private long roomID = -1;
225 226 227 228 229 230 231 232 233 234 235

    /**
     * The date when the room was created.
     */
    private Date creationDate;

    /**
     * The last date when the room's configuration was modified.
     */
    private Date modificationDate;

236 237 238 239 240 241
    /**
     * The date when the last occupant left the room. A null value means that there are occupants
     * in the room at the moment.
     */
    private Date emptyDate;

Matt Tucker's avatar
Matt Tucker committed
242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
    /**
     * Indicates if the room is present in the database.
     */
    private boolean savedToDB = false;

    /**
     * Create a new chat room.
     * 
     * @param chatserver the server hosting the room.
     * @param roomname the name of the room.
     * @param packetRouter the router for sending packets from the room.
     */
    MUCRoomImpl(MultiUserChatServer chatserver, String roomname, PacketRouter packetRouter) {
        this.server = chatserver;
        this.name = roomname;
257
        this.naturalLanguageName = roomname;
Matt Tucker's avatar
Matt Tucker committed
258 259 260
        this.description = roomname;
        this.router = packetRouter;
        this.startTime = System.currentTimeMillis();
261 262
        this.creationDate = new Date(startTime);
        this.modificationDate = new Date(startTime);
263
        this.emptyDate = new Date(startTime);
Matt Tucker's avatar
Matt Tucker committed
264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293
        // TODO Allow to set the history strategy from the configuration form?
        roomHistory = new MUCRoomHistory(this, new HistoryStrategy(server.getHistoryStrategy()));
        role = new RoomRole(this);
        this.iqOwnerHandler = new IQOwnerHandler(this, packetRouter);
        this.iqAdminHandler = new IQAdminHandler(this, packetRouter);
        // No one can join the room except the room's owner
        this.lockedTime = startTime;
        // Set the default roles for which presence is broadcast
        rolesToBroadcastPresence.add("moderator");
        rolesToBroadcastPresence.add("participant");
        rolesToBroadcastPresence.add("visitor");
    }

    public String getName() {
        return name;
    }

    public long getID() {
        if (isPersistent() || isLogEnabled()) {
            if (roomID == -1) {
                roomID = SequenceManager.nextID(JiveConstants.MUC_ROOM);
            }
        }
        return roomID;
    }

    public void setID(long roomID) {
        this.roomID = roomID;
    }

294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309
    public Date getCreationDate() {
        return creationDate;
    }

    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }

    public Date getModificationDate() {
        return modificationDate;
    }

    public void setModificationDate(Date modificationDate) {
        this.modificationDate = modificationDate;
    }

310 311 312 313 314 315 316 317 318 319 320 321 322
    public void setEmptyDate(Date emptyDate) {
        // Do nothing if old value is same as new value
        if (this.emptyDate == emptyDate) {
            return;
        }
        this.emptyDate = emptyDate;
        MUCPersistenceManager.updateRoomEmptyDate(this);
    }

    public Date getEmptyDate() {
        return this.emptyDate;
    }

Matt Tucker's avatar
Matt Tucker committed
323 324 325 326 327
    public MUCRole getRole() {
        return role;
    }

    public MUCRole getOccupant(String nickname) throws UserNotFoundException {
328 329 330
        if (nickname == null) {
             throw new UserNotFoundException();
        }
331 332 333
        MUCRole role = occupants.get(nickname.toLowerCase());
        if (role != null) {
            return role;
Matt Tucker's avatar
Matt Tucker committed
334
        }
335
        throw new UserNotFoundException();
Matt Tucker's avatar
Matt Tucker committed
336 337 338
    }

    public List<MUCRole> getOccupantsByBareJID(String jid) throws UserNotFoundException {
339 340
        List<MUCRole> roles = occupantsByBareJID.get(jid);
        if (roles != null && !roles.isEmpty()) {
341
            return Collections.unmodifiableList(roles);
Matt Tucker's avatar
Matt Tucker committed
342
        }
343
        throw new UserNotFoundException();
Matt Tucker's avatar
Matt Tucker committed
344 345 346
    }

    public MUCRole getOccupantByFullJID(String jid) throws UserNotFoundException {
347 348 349
        MUCRole role = occupantsByFullJID.get(jid);
        if (role != null) {
            return role;
Matt Tucker's avatar
Matt Tucker committed
350
        }
351
        throw new UserNotFoundException();
Matt Tucker's avatar
Matt Tucker committed
352 353
    }

354 355
    public Collection<MUCRole> getOccupants() {
        return Collections.unmodifiableCollection(occupants.values());
Matt Tucker's avatar
Matt Tucker committed
356 357 358 359 360 361
    }

    public int getOccupantsCount() {
        return occupants.size();
    }

362
    public boolean hasOccupant(String nickname) {
363
        return occupants.containsKey(nickname.toLowerCase());
Matt Tucker's avatar
Matt Tucker committed
364 365 366
    }

    public String getReservedNickname(String bareJID) {
367 368 369
        String answer = members.get(bareJID);
        if (answer == null || answer.trim().length() == 0) {
            return null;
Matt Tucker's avatar
Matt Tucker committed
370
        }
371
        return answer;
Matt Tucker's avatar
Matt Tucker committed
372 373
    }

Matt Tucker's avatar
Matt Tucker committed
374
    public MUCRole.Affiliation getAffiliation(String bareJID) {
Matt Tucker's avatar
Matt Tucker committed
375
        if (owners.contains(bareJID)) {
Matt Tucker's avatar
Matt Tucker committed
376
            return MUCRole.Affiliation.owner;
Matt Tucker's avatar
Matt Tucker committed
377 378
        }
        else if (admins.contains(bareJID)) {
Matt Tucker's avatar
Matt Tucker committed
379
            return MUCRole.Affiliation.admin;
Matt Tucker's avatar
Matt Tucker committed
380 381
        }
        else if (members.containsKey(bareJID)) {
Matt Tucker's avatar
Matt Tucker committed
382
            return MUCRole.Affiliation.member;
Matt Tucker's avatar
Matt Tucker committed
383 384
        }
        else if (outcasts.contains(bareJID)) {
Matt Tucker's avatar
Matt Tucker committed
385
            return MUCRole.Affiliation.outcast;
Matt Tucker's avatar
Matt Tucker committed
386
        }
Matt Tucker's avatar
Matt Tucker committed
387
        return MUCRole.Affiliation.none;
Matt Tucker's avatar
Matt Tucker committed
388 389 390
    }

    public MUCRole joinRoom(String nickname, String password, HistoryRequest historyRequest,
391 392
            MUCUser user, Presence presence) throws UnauthorizedException,
            UserAlreadyExistsException, RoomLockedException, ForbiddenException,
393
            RegistrationRequiredException, ConflictException, ServiceUnavailableException {
Matt Tucker's avatar
Matt Tucker committed
394 395 396
        MUCRoleImpl joinRole = null;
        lock.writeLock().lock();
        try {
397
            // If the room has a limit of max user then check if the limit has been reached
398
            if (isDestroyed || (getMaxUsers() > 0 && getOccupantsCount() >= getMaxUsers())) {
399
                throw new ServiceUnavailableException();
Matt Tucker's avatar
Matt Tucker committed
400
            }
401
            boolean isOwner = owners.contains(user.getAddress().toBareJID());
Matt Tucker's avatar
Matt Tucker committed
402
            // If the room is locked and this user is not an owner raise a RoomLocked exception
403
            if (isLocked()) {
Matt Tucker's avatar
Matt Tucker committed
404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421
                if (!isOwner) {
                    throw new RoomLockedException();
                }
            }
            // If the user is already in the room raise a UserAlreadyExists exception
            if (occupants.containsKey(nickname.toLowerCase())) {
                throw new UserAlreadyExistsException();
            }
            // If the room is password protected and the provided password is incorrect raise a
            // Unauthorized exception
            if (isPasswordProtected()) {
                if (password == null || !password.equals(getPassword())) {
                    throw new UnauthorizedException();
                }
            }
            // If another user attempts to join the room with a nickname reserved by the first user
            // raise a ConflictException
            if (members.containsValue(nickname)) {
422
                if (!nickname.equals(members.get(user.getAddress().toBareJID()))) {
Matt Tucker's avatar
Matt Tucker committed
423 424 425 426 427
                    throw new ConflictException();
                }
            }

            // Set the corresponding role based on the user's affiliation
Matt Tucker's avatar
Matt Tucker committed
428 429
            MUCRole.Role role;
            MUCRole.Affiliation affiliation;
Matt Tucker's avatar
Matt Tucker committed
430 431
            if (isOwner) {
                // The user is an owner. Set the role and affiliation accordingly.
Matt Tucker's avatar
Matt Tucker committed
432 433
                role = MUCRole.Role.moderator;
                affiliation = MUCRole.Affiliation.owner;
Matt Tucker's avatar
Matt Tucker committed
434
            }
435
            else if (server.getSysadmins().contains(user.getAddress().toBareJID())) {
Matt Tucker's avatar
Matt Tucker committed
436 437
                // The user is a system administrator of the MUC service. Treat him as an owner 
                // although he won't appear in the list of owners
Matt Tucker's avatar
Matt Tucker committed
438 439
                role = MUCRole.Role.moderator;
                affiliation = MUCRole.Affiliation.owner;
Matt Tucker's avatar
Matt Tucker committed
440
            }
441
            else if (admins.contains(user.getAddress().toBareJID())) {
Matt Tucker's avatar
Matt Tucker committed
442
                // The user is an admin. Set the role and affiliation accordingly.
Matt Tucker's avatar
Matt Tucker committed
443 444
                role = MUCRole.Role.moderator;
                affiliation = MUCRole.Affiliation.admin;
Matt Tucker's avatar
Matt Tucker committed
445
            }
446
            else if (members.containsKey(user.getAddress().toBareJID())) {
Matt Tucker's avatar
Matt Tucker committed
447
                // The user is a member. Set the role and affiliation accordingly.
Matt Tucker's avatar
Matt Tucker committed
448 449
                role = MUCRole.Role.participant;
                affiliation = MUCRole.Affiliation.member;
Matt Tucker's avatar
Matt Tucker committed
450
            }
451
            else if (outcasts.contains(user.getAddress().toBareJID())) {
Matt Tucker's avatar
Matt Tucker committed
452 453 454 455 456
                // The user is an outcast. Raise a "Forbidden" exception.
                throw new ForbiddenException();
            }
            else {
                // The user has no affiliation (i.e. NONE). Set the role accordingly.
457
                if (isMembersOnly()) {
Matt Tucker's avatar
Matt Tucker committed
458 459 460 461
                    // The room is members-only and the user is not a member. Raise a
                    // "Registration Required" exception.
                    throw new RegistrationRequiredException();
                }
Matt Tucker's avatar
Matt Tucker committed
462 463
                role = (isModerated() ? MUCRole.Role.visitor : MUCRole.Role.participant);
                affiliation = MUCRole.Affiliation.none;
Matt Tucker's avatar
Matt Tucker committed
464 465
            }
            // Create a new role for this user in this room
466 467 468
            joinRole =
                    new MUCRoleImpl(server, this, nickname, role, affiliation, (MUCUserImpl) user,
                            presence, router);
Matt Tucker's avatar
Matt Tucker committed
469 470 471
            // Add the new user as an occupant of this room
            occupants.put(nickname.toLowerCase(), joinRole);
            // Update the tables of occupants based on the bare and full JID
472
            List<MUCRole> list = occupantsByBareJID.get(user.getAddress().toBareJID());
Matt Tucker's avatar
Matt Tucker committed
473 474
            if (list == null) {
                list = new ArrayList<MUCRole>();
475
                occupantsByBareJID.put(user.getAddress().toBareJID(), list);
Matt Tucker's avatar
Matt Tucker committed
476 477
            }
            list.add(joinRole);
478
            occupantsByFullJID.put(user.getAddress(), joinRole);
Matt Tucker's avatar
Matt Tucker committed
479 480 481 482
        }
        finally {
            lock.writeLock().unlock();
        }
483 484 485 486 487 488 489 490
        // Send presence of existing occupants to new occupant
        sendInitialPresences(joinRole);
        // It is assumed that the room is new based on the fact that it's locked and
        // that it was locked when it was created.
        boolean isRoomNew = isLocked() && creationDate.getTime() == lockedTime;
        try {
            // Send the presence of this new occupant to existing occupants
            Presence joinPresence = joinRole.getPresence().createCopy();
Matt Tucker's avatar
Matt Tucker committed
491
            if (isRoomNew) {
492 493 494
                Element frag = joinPresence.getChildElement(
                        "x", "http://jabber.org/protocol/muc#user");
                frag.addElement("status").addAttribute("code", "201");
495
            }
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532
            broadcastPresence(joinPresence);
        }
        catch (Exception e) {
            Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
        }
        // If the room has just been created send the "room locked until configuration is
        // confirmed" message
        if (isRoomNew) {
            Message message = new Message();
            message.setType(Message.Type.groupchat);
            message.setBody(LocaleUtils.getLocalizedString("muc.new"));
            message.setFrom(role.getRoleAddress());
            joinRole.send(message);
        }
        else if (isLocked()) {
            // Warn the owner that the room is locked but it's not new
            Message message = new Message();
            message.setType(Message.Type.groupchat);
            message.setBody(LocaleUtils.getLocalizedString("muc.locked"));
            message.setFrom(role.getRoleAddress());
            joinRole.send(message);
        }
        else if (canAnyoneDiscoverJID()) {
            // Warn the new occupant that the room is non-anonymous (i.e. his JID will be
            // public)
            Message message = new Message();
            message.setType(Message.Type.groupchat);
            message.setBody(LocaleUtils.getLocalizedString("muc.warnnonanonymous"));
            message.setFrom(role.getRoleAddress());
            Element frag = message.addChildElement("x", "http://jabber.org/protocol/muc#user");
            frag.addElement("status").addAttribute("code", "100");
            joinRole.send(message);
        }
        if (historyRequest == null) {
            Iterator history = roomHistory.getMessageHistory();
            while (history.hasNext()) {
                joinRole.send((Message) history.next());
Matt Tucker's avatar
Matt Tucker committed
533
            }
534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551
        }
        else {
            historyRequest.sendHistory(joinRole, roomHistory);
        }
        // Update the date when the last occupant left the room
        setEmptyDate(null);
        return joinRole;
    }

    /**
     * Sends presence of existing occupants to new occupant.
     *
     * @param joinRole the role of the new occupant in the room.
     */
    private void sendInitialPresences(MUCRoleImpl joinRole) {
        for (MUCRole occupant : occupants.values()) {
            if (occupant == joinRole) {
                continue;
Matt Tucker's avatar
Matt Tucker committed
552
            }
553 554 555 556 557 558 559 560
            Presence occupantPresence = occupant.getPresence().createCopy();
            // Skip to the next occupant if we cannot send presence of this occupant
            if (hasToCheckRoleToBroadcastPresence()) {
                Element frag = occupantPresence.getChildElement("x",
                        "http://jabber.org/protocol/muc#user");
                // Check if we can broadcast the presence for this role
                if (!canBroadcastPresence(frag.element("item").attributeValue("role"))) {
                    continue;
Matt Tucker's avatar
Matt Tucker committed
561 562
                }
            }
563 564
            // Don't include the occupant's JID if the room is semi-anon and the new occupant
            // is not a moderator
Matt Tucker's avatar
Matt Tucker committed
565
            if (!canAnyoneDiscoverJID() && MUCRole.Role.moderator != joinRole.getRole()) {
566 567 568
                Element frag = occupantPresence.getChildElement("x",
                        "http://jabber.org/protocol/muc#user");
                frag.element("item").addAttribute("jid", null);
Matt Tucker's avatar
Matt Tucker committed
569
            }
570
            joinRole.send(occupantPresence);
Matt Tucker's avatar
Matt Tucker committed
571 572 573
        }
    }

574
    public void leaveRoom(String nickname) throws UserNotFoundException {
Matt Tucker's avatar
Matt Tucker committed
575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
        MUCRole leaveRole = null;
        lock.writeLock().lock();
        try {
            leaveRole = occupants.remove(nickname.toLowerCase());
            if (leaveRole == null) {
                throw new UserNotFoundException();
            }
            // Removes the role from the room
            removeOccupantRole(leaveRole);

            // TODO Implement this: If the room owner becomes unavailable for any reason before
            // submitting the form (e.g., a lost connection), the service will receive a presence
            // stanza of type "unavailable" from the owner to the room@service/nick or room@service
            // (or both). The service MUST then destroy the room, sending a presence stanza of type
            // "unavailable" from the room to the owner including a <destroy/> element and reason
            // (if provided) as defined under the "Destroying a Room" use case.

592 593 594
            // Remove the room from the server only if there are no more occupants and the room is
            // not persistent
            if (occupants.isEmpty() && !isPersistent()) {
Matt Tucker's avatar
Matt Tucker committed
595 596 597
                endTime = System.currentTimeMillis();
                server.removeChatRoom(name);
            }
598 599 600 601
            if (occupants.isEmpty()) {
                // Update the date when the last occupant left the room
                setEmptyDate(new Date());
            }
Matt Tucker's avatar
Matt Tucker committed
602 603 604 605 606
        }
        finally {
            lock.writeLock().unlock();
        }

607 608 609 610
        try {
            Presence presence = leaveRole.getPresence().createCopy();
            presence.setType(Presence.Type.unavailable);
            presence.setStatus(null);
611 612 613
            // Inform the leaving user that he/she has left the room
            leaveRole.send(presence);
            // Inform the rest of the room occupants that the user has left the room
614 615 616 617
            broadcastPresence(presence);
        }
        catch (Exception e) {
            Log.error(e);
Matt Tucker's avatar
Matt Tucker committed
618 619 620 621
        }
    }

    /**
622 623 624 625
     * Removes the role of the occupant from all the internal occupants collections. The role will
     * also be removed from the user's roles.
     *
     * @param leaveRole the role to remove.
Matt Tucker's avatar
Matt Tucker committed
626 627 628 629 630
     */
    private void removeOccupantRole(MUCRole leaveRole) {
        occupants.remove(leaveRole.getNickname().toLowerCase());

        MUCUser user = leaveRole.getChatUser();
631 632
        // Notify the user that he/she is no longer in the room
        user.removeRole(getName());
Matt Tucker's avatar
Matt Tucker committed
633
        // Update the tables of occupants based on the bare and full JID
634
        List list = occupantsByBareJID.get(user.getAddress().toBareJID());
Matt Tucker's avatar
Matt Tucker committed
635 636 637
        if (list != null) {
            list.remove(leaveRole);
            if (list.isEmpty()) {
638
                occupantsByBareJID.remove(user.getAddress().toBareJID());
Matt Tucker's avatar
Matt Tucker committed
639 640
            }
        }
641
        occupantsByFullJID.remove(user.getAddress().toString());
Matt Tucker's avatar
Matt Tucker committed
642 643
    }

644
    public void destroyRoom(String alternateJID, String reason) {
Matt Tucker's avatar
Matt Tucker committed
645
        MUCRole leaveRole = null;
646
        Collection<MUCRole> removedRoles = new ArrayList<MUCRole>();
Matt Tucker's avatar
Matt Tucker committed
647 648 649 650 651 652 653
        lock.writeLock().lock();
        try {
            // Remove each occupant
            for (String nickname: occupants.keySet()) {
                leaveRole = occupants.remove(nickname);

                if (leaveRole != null) {
654 655 656 657
                    // Add the removed occupant to the list of removed occupants. We are keeping a
                    // list of removed occupants to process later outside of the lock.
                    removedRoles.add(leaveRole);
                    removeOccupantRole(leaveRole);
Matt Tucker's avatar
Matt Tucker committed
658 659 660
                }
            }
            endTime = System.currentTimeMillis();
661
            // Removes the room from the list of rooms hosted in the server
Matt Tucker's avatar
Matt Tucker committed
662
            server.removeChatRoom(name);
663 664
            // Set that the room has been destroyed
            isDestroyed = true;
Matt Tucker's avatar
Matt Tucker committed
665 666 667 668
        }
        finally {
            lock.writeLock().unlock();
        }
669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699
        // Send an unavailable presence to each removed occupant
        for (MUCRole removedRole : removedRoles) {
            try {
                // Send a presence stanza of type "unavailable" to the occupant
                Presence presence = createPresence(Presence.Type.unavailable);
                presence.setFrom(removedRole.getRoleAddress());

                // A fragment containing the x-extension for room destruction.
                Element fragment = presence.addChildElement("x",
                        "http://jabber.org/protocol/muc#user");
                Element item = fragment.addElement("item");
                item.addAttribute("affiliation", "none");
                item.addAttribute("role", "none");
                if (alternateJID != null && alternateJID.length() > 0) {
                    fragment.addElement("destroy").addAttribute("jid", alternateJID);
                }
                if (reason != null && reason.length() > 0) {
                    Element destroy = fragment.element("destroy");
                    if (destroy == null) {
                        destroy = fragment.addElement("destroy");
                    }
                    destroy.addElement("reason").setText(reason);
                }
                removedRole.send(presence);
            }
            catch (Exception e) {
                Log.error(e);
            }
        }
        // Remove the room from the DB if the room was persistent
        MUCPersistenceManager.deleteFromDB(this);
Matt Tucker's avatar
Matt Tucker committed
700 701
    }

702 703 704 705
    public Presence createPresence(Presence.Type presenceType) throws UnauthorizedException {
        Presence presence = new Presence();
        presence.setType(presenceType);
        presence.setFrom(role.getRoleAddress());
Matt Tucker's avatar
Matt Tucker committed
706 707 708
        return presence;
    }

709
    public void serverBroadcast(String msg) {
710 711
        Message message = new Message();
        message.setType(Message.Type.groupchat);
Matt Tucker's avatar
Matt Tucker committed
712
        message.setBody(msg);
713
        message.setFrom(role.getRoleAddress());
Matt Tucker's avatar
Matt Tucker committed
714 715 716 717
        roomHistory.addMessage(message);
        broadcast(message);
    }

718
    public void sendPublicMessage(Message message, MUCRole senderRole) throws ForbiddenException {
Matt Tucker's avatar
Matt Tucker committed
719
        // Check that if the room is moderated then the sender of the message has to have voice
Matt Tucker's avatar
Matt Tucker committed
720
        if (isModerated() && senderRole.getRole().compareTo(MUCRole.Role.participant) > 0) {
Matt Tucker's avatar
Matt Tucker committed
721 722 723
            throw new ForbiddenException();
        }
        // Send the message to all occupants
724
        message.setFrom(senderRole.getRoleAddress());
Matt Tucker's avatar
Matt Tucker committed
725 726 727 728
        send(message);
    }

    public void sendPrivateMessage(Message message, MUCRole senderRole) throws NotFoundException {
Derek DeMoro's avatar
Derek DeMoro committed
729
        String resource = message.getTo().getResource();
Matt Tucker's avatar
Matt Tucker committed
730 731
        MUCRole occupant = occupants.get(resource.toLowerCase());
        if (occupant != null) {
732
            message.setFrom(senderRole.getRoleAddress());
733
            occupant.send(message);
Matt Tucker's avatar
Matt Tucker committed
734 735 736 737 738 739
        }
        else {
            throw new NotFoundException();
        }
    }

Matt Tucker's avatar
Matt Tucker committed
740 741 742 743 744 745 746 747 748
    public void send(Packet packet) {
        if (packet instanceof Message) {
            roomHistory.addMessage((Message)packet);
            broadcast((Message)packet);
        }
        else if (packet instanceof Presence) {
            broadcastPresence((Presence)packet);
        }
        else if (packet instanceof IQ) {
749 750 751 752
            IQ reply = IQ.createResultIQ((IQ) packet);
            reply.setChildElement(((IQ) packet).getChildElement());
            reply.setError(PacketError.Condition.bad_request);
            router.route(reply);
Matt Tucker's avatar
Matt Tucker committed
753
        }
Matt Tucker's avatar
Matt Tucker committed
754 755
    }

756 757 758 759 760 761 762 763
    /**
     * Broadcasts the specified presence to all room occupants. If the presence belongs to a
     * user whose role cannot be broadcast then the presence will only be sent to the presence's
     * user. On the other hand, the JID of the user that sent the presence won't be included if the
     * room is semi-anon and the target occupant is not a moderator.
     *
     * @param presence the presence to broadcast.
     */
Matt Tucker's avatar
Matt Tucker committed
764 765 766 767
    private void broadcastPresence(Presence presence) {
        if (presence == null) {
            return;
        }
768
        Element frag = null;
Matt Tucker's avatar
Matt Tucker committed
769 770
        String jid = null;
        if (hasToCheckRoleToBroadcastPresence()) {
771
            frag = presence.getChildElement("x", "http://jabber.org/protocol/muc#user");
Matt Tucker's avatar
Matt Tucker committed
772
            // Check if we can broadcast the presence for this role
773
            if (!canBroadcastPresence(frag.element("item").attributeValue("role"))) {
Matt Tucker's avatar
Matt Tucker committed
774 775
                // Just send the presence to the sender of the presence
                try {
776
                    MUCRole occupant = getOccupant(presence.getFrom().getResource());
777
                    occupant.send(presence);
Matt Tucker's avatar
Matt Tucker committed
778 779 780 781 782 783 784 785 786 787 788 789
                }
                catch (UserNotFoundException e) {
                    // Do nothing
                }
                return;
            }
        }

        // Don't include the occupant's JID if the room is semi-anon and the new occupant
        // is not a moderator
        if (!canAnyoneDiscoverJID()) {
            if (frag == null) {
790
                frag = presence.getChildElement("x", "http://jabber.org/protocol/muc#user");
Matt Tucker's avatar
Matt Tucker committed
791
            }
792
            jid = frag.element("item").attributeValue("jid");
Matt Tucker's avatar
Matt Tucker committed
793
        }
794 795 796 797
        for (MUCRole occupant : occupants.values()) {
            // Don't include the occupant's JID if the room is semi-anon and the new occupant
            // is not a moderator
            if (!canAnyoneDiscoverJID()) {
Matt Tucker's avatar
Matt Tucker committed
798
                if (MUCRole.Role.moderator == occupant.getRole()) {
799
                    frag.element("item").addAttribute("jid", jid);
800 801
                }
                else {
802
                    frag.element("item").addAttribute("jid", null);
Matt Tucker's avatar
Matt Tucker committed
803 804
                }
            }
805
            occupant.send(presence);
Matt Tucker's avatar
Matt Tucker committed
806 807 808 809
        }
    }

    private void broadcast(Message message) {
810 811 812 813 814 815 816 817
        for (MUCRole occupant : occupants.values()) {
            occupant.send(message);
        }
        if (isLogEnabled()) {
            MUCRole senderRole = null;
            JID senderAddress = null;
            if (message.getTo() != null && message.getTo().getResource() != null) {
                senderRole = occupants.get(message.getTo().getResource());
Matt Tucker's avatar
Matt Tucker committed
818
            }
819 820 821
            if (senderRole == null) {
                // The room itself is sending the message
                senderAddress = getRole().getRoleAddress();
Matt Tucker's avatar
Matt Tucker committed
822
            }
823 824 825 826 827 828
            else {
                // An occupant is sending the message
                senderAddress = senderRole.getChatUser().getAddress();
            }
            // Log the conversation
            server.logConversation(this, message, senderAddress);
Matt Tucker's avatar
Matt Tucker committed
829 830 831 832 833 834 835 836 837 838 839 840 841 842 843
        }
    }

    /**
     * An empty role that represents the room itself in the chatroom. Chatrooms need to be able to
     * speak (server messages) and so must have their own role in the chatroom.
     */
    private class RoomRole implements MUCRole {

        private MUCRoom room;

        private RoomRole(MUCRoom room) {
            this.room = room;
        }

844
        public Presence getPresence() {
Matt Tucker's avatar
Matt Tucker committed
845 846 847
            return null;
        }

848
        public Element getExtendedPresenceInformation() {
Matt Tucker's avatar
Matt Tucker committed
849 850 851
            return null;
        }

852
        public void setPresence(Presence presence) {
Matt Tucker's avatar
Matt Tucker committed
853 854
        }

Matt Tucker's avatar
Matt Tucker committed
855
        public void setRole(MUCRole.Role newRole) {
Matt Tucker's avatar
Matt Tucker committed
856 857
        }

Matt Tucker's avatar
Matt Tucker committed
858 859
        public MUCRole.Role getRole() {
            return MUCRole.Role.moderator;
Matt Tucker's avatar
Matt Tucker committed
860 861
        }

Matt Tucker's avatar
Matt Tucker committed
862
        public void setAffiliation(MUCRole.Affiliation newAffiliation) {
Matt Tucker's avatar
Matt Tucker committed
863 864
        }

Matt Tucker's avatar
Matt Tucker committed
865 866
        public MUCRole.Affiliation getAffiliation() {
            return MUCRole.Affiliation.owner;
Matt Tucker's avatar
Matt Tucker committed
867 868 869 870 871 872 873 874 875 876 877 878 879 880
        }

        public String getNickname() {
            return null;
        }

        public MUCUser getChatUser() {
            return null;
        }

        public MUCRoom getChatRoom() {
            return room;
        }

881
        private JID crJID = null;
Matt Tucker's avatar
Matt Tucker committed
882

883
        public JID getRoleAddress() {
Matt Tucker's avatar
Matt Tucker committed
884
            if (crJID == null) {
885
                crJID = new JID(room.getName(), server.getServiceDomain(), "");
Matt Tucker's avatar
Matt Tucker committed
886 887 888 889
            }
            return crJID;
        }

Matt Tucker's avatar
Matt Tucker committed
890
        public void send(Packet packet) {
Matt Tucker's avatar
Matt Tucker committed
891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
            room.send(packet);
        }

        public void changeNickname(String nickname) {
        }
    }

    public long getChatLength() {
        return endTime - startTime;
    }

    /**
     * Updates all the presences of the given user with the new affiliation and role information. Do
     * nothing if the given jid is not present in the room. If the user has joined the room from
     * several client resources, all his/her occupants' presences will be updated.
     * 
     * @param bareJID the bare jid of the user to update his/her role.
     * @param newAffiliation the new affiliation for the JID.
     * @param newRole the new role for the JID.
     * @return the list of updated presences of all the client resources that the client used to
     *         join the room.
Gaston Dombiak's avatar
Gaston Dombiak committed
912 913
     * @throws NotAllowedException If trying to change the moderator role to an owner or an admin or
     *         if trying to ban an owner or an administrator.
Matt Tucker's avatar
Matt Tucker committed
914
     */
Matt Tucker's avatar
Matt Tucker committed
915
    private List<Presence> changeOccupantAffiliation(String bareJID, MUCRole.Affiliation newAffiliation, MUCRole.Role newRole)
Matt Tucker's avatar
Matt Tucker committed
916
            throws NotAllowedException {
917
        List<Presence> presences = new ArrayList<Presence>();
Matt Tucker's avatar
Matt Tucker committed
918
        // Get all the roles (i.e. occupants) of this user based on his/her bare JID
Gaston Dombiak's avatar
Gaston Dombiak committed
919
        List<MUCRole> roles = occupantsByBareJID.get(bareJID);
Matt Tucker's avatar
Matt Tucker committed
920 921 922 923
        if (roles == null) {
            return presences;
        }
        // Collect all the updated presences of these roles
Gaston Dombiak's avatar
Gaston Dombiak committed
924
        for (MUCRole role : roles) {
925 926 927 928
            // Update the presence with the new affiliation and role
            role.setAffiliation(newAffiliation);
            role.setRole(newRole);
            // Prepare a new presence to be sent to all the room occupants
929
            presences.add(role.getPresence().createCopy());
Matt Tucker's avatar
Matt Tucker committed
930 931 932 933 934 935 936 937 938
        }
        // Answer all the updated presences
        return presences;
    }

    /**
     * Updates the presence of the given user with the new role information. Do nothing if the given
     * jid is not present in the room.
     * 
939
     * @param jid the full jid of the user to update his/her role.
Matt Tucker's avatar
Matt Tucker committed
940 941
     * @param newRole the new role for the JID.
     * @return the updated presence of the user or null if none.
Gaston Dombiak's avatar
Gaston Dombiak committed
942
     * @throws NotAllowedException If trying to change the moderator role to an owner or an admin.
Matt Tucker's avatar
Matt Tucker committed
943
     */
Matt Tucker's avatar
Matt Tucker committed
944
    private Presence changeOccupantRole(JID jid, MUCRole.Role newRole) throws NotAllowedException {
Matt Tucker's avatar
Matt Tucker committed
945
        // Try looking the role in the bare JID list
946
        MUCRole role = occupantsByFullJID.get(jid);
Matt Tucker's avatar
Matt Tucker committed
947
        if (role != null) {
948 949 950
            // Update the presence with the new role
            role.setRole(newRole);
            // Prepare a new presence to be sent to all the room occupants
951
            return role.getPresence().createCopy();
Matt Tucker's avatar
Matt Tucker committed
952 953 954 955 956 957 958 959
        }
        return null;
    }

    public void addFirstOwner(String bareJID) {
        owners.add(bareJID);
    }

960
    public List<Presence> addOwner(String bareJID, MUCRole sendRole) throws ForbiddenException {
Matt Tucker's avatar
Matt Tucker committed
961 962
        MUCRole.Affiliation oldAffiliation = MUCRole.Affiliation.none;
        if (MUCRole.Affiliation.owner != sendRole.getAffiliation()) {
Matt Tucker's avatar
Matt Tucker committed
963 964 965 966 967
            throw new ForbiddenException();
        }
        owners.add(bareJID);
        // Remove the user from other affiliation lists
        if (removeAdmin(bareJID)) {
Matt Tucker's avatar
Matt Tucker committed
968
            oldAffiliation = MUCRole.Affiliation.admin;
Matt Tucker's avatar
Matt Tucker committed
969 970
        }
        else if (removeMember(bareJID)) {
Matt Tucker's avatar
Matt Tucker committed
971
            oldAffiliation = MUCRole.Affiliation.member;
Matt Tucker's avatar
Matt Tucker committed
972 973
        }
        else if (removeOutcast(bareJID)) {
Matt Tucker's avatar
Matt Tucker committed
974
            oldAffiliation = MUCRole.Affiliation.outcast;
Matt Tucker's avatar
Matt Tucker committed
975 976 977 978 979 980
        }
        // Update the DB if the room is persistent
        MUCPersistenceManager.saveAffiliationToDB(
            this,
            bareJID,
            null,
Matt Tucker's avatar
Matt Tucker committed
981
            MUCRole.Affiliation.owner,
Matt Tucker's avatar
Matt Tucker committed
982 983 984
            oldAffiliation);
        // Update the presence with the new affiliation and inform all occupants
        try {
Matt Tucker's avatar
Matt Tucker committed
985 986
            return changeOccupantAffiliation(bareJID, MUCRole.Affiliation.owner,
                    MUCRole.Role.moderator);
Matt Tucker's avatar
Matt Tucker committed
987 988 989 990 991 992 993 994 995 996 997
        }
        catch (NotAllowedException e) {
            // We should never receive this exception....in theory
            return null;
        }
    }

    private boolean removeOwner(String bareJID) {
        return owners.remove(bareJID);
    }

998
    public List<Presence> addAdmin(String bareJID, MUCRole sendRole) throws ForbiddenException,
Matt Tucker's avatar
Matt Tucker committed
999
            ConflictException {
Matt Tucker's avatar
Matt Tucker committed
1000 1001
        MUCRole.Affiliation oldAffiliation = MUCRole.Affiliation.none;
        if (MUCRole.Affiliation.owner != sendRole.getAffiliation()) {
Matt Tucker's avatar
Matt Tucker committed
1002 1003 1004 1005 1006 1007 1008 1009 1010
            throw new ForbiddenException();
        }
        // Check that the room always has an owner
        if (owners.contains(bareJID) && owners.size() == 1) {
            throw new ConflictException();
        }
        admins.add(bareJID);
        // Remove the user from other affiliation lists
        if (removeOwner(bareJID)) {
Matt Tucker's avatar
Matt Tucker committed
1011
            oldAffiliation = MUCRole.Affiliation.owner;
Matt Tucker's avatar
Matt Tucker committed
1012 1013
        }
        else if (removeMember(bareJID)) {
Matt Tucker's avatar
Matt Tucker committed
1014
            oldAffiliation = MUCRole.Affiliation.member;
Matt Tucker's avatar
Matt Tucker committed
1015 1016
        }
        else if (removeOutcast(bareJID)) {
Matt Tucker's avatar
Matt Tucker committed
1017
            oldAffiliation = MUCRole.Affiliation.outcast;
Matt Tucker's avatar
Matt Tucker committed
1018 1019 1020 1021 1022 1023
        }
        // Update the DB if the room is persistent
        MUCPersistenceManager.saveAffiliationToDB(
            this,
            bareJID,
            null,
Matt Tucker's avatar
Matt Tucker committed
1024
            MUCRole.Affiliation.admin,
Matt Tucker's avatar
Matt Tucker committed
1025 1026 1027
            oldAffiliation);
        // Update the presence with the new affiliation and inform all occupants
        try {
Matt Tucker's avatar
Matt Tucker committed
1028 1029
            return changeOccupantAffiliation(bareJID, MUCRole.Affiliation.admin,
                    MUCRole.Role.moderator);
Matt Tucker's avatar
Matt Tucker committed
1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040
        }
        catch (NotAllowedException e) {
            // We should never receive this exception....in theory
            return null;
        }
    }

    private boolean removeAdmin(String bareJID) {
        return admins.remove(bareJID);
    }

1041
    public List<Presence> addMember(String bareJID, String nickname, MUCRole sendRole)
Matt Tucker's avatar
Matt Tucker committed
1042
            throws ForbiddenException, ConflictException {
Matt Tucker's avatar
Matt Tucker committed
1043 1044
        MUCRole.Affiliation oldAffiliation = (members.containsKey(bareJID) ?
                MUCRole.Affiliation.member : MUCRole.Affiliation.none);
1045
        if (isMembersOnly()) {
Matt Tucker's avatar
Matt Tucker committed
1046
            if (!canOccupantsInvite()) {
Matt Tucker's avatar
Matt Tucker committed
1047 1048
                if (MUCRole.Affiliation.admin != sendRole.getAffiliation()
                        && MUCRole.Affiliation.owner != sendRole.getAffiliation()) {
Matt Tucker's avatar
Matt Tucker committed
1049 1050 1051 1052 1053
                    throw new ForbiddenException();
                }
            }
        }
        else {
Matt Tucker's avatar
Matt Tucker committed
1054 1055
            if (MUCRole.Affiliation.admin != sendRole.getAffiliation()
                    && MUCRole.Affiliation.owner != sendRole.getAffiliation()) {
Matt Tucker's avatar
Matt Tucker committed
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073
                throw new ForbiddenException();
            }
        }
        // Check if the desired nickname is already reserved for another member
        if (nickname != null && nickname.trim().length() > 0 && members.containsValue(nickname)) {
            if (!nickname.equals(members.get(bareJID))) {
                throw new ConflictException();
            }
        }
        // Check that the room always has an owner
        if (owners.contains(bareJID) && owners.size() == 1) {
            throw new ConflictException();
        }
        // Associate the reserved nickname with the bareJID. If nickname is null then associate an
        // empty string
        members.put(bareJID, (nickname == null ? "" : nickname));
        // Remove the user from other affiliation lists
        if (removeOwner(bareJID)) {
Matt Tucker's avatar
Matt Tucker committed
1074
            oldAffiliation = MUCRole.Affiliation.owner;
Matt Tucker's avatar
Matt Tucker committed
1075 1076
        }
        else if (removeAdmin(bareJID)) {
Matt Tucker's avatar
Matt Tucker committed
1077
            oldAffiliation = MUCRole.Affiliation.admin;
Matt Tucker's avatar
Matt Tucker committed
1078 1079
        }
        else if (removeOutcast(bareJID)) {
Matt Tucker's avatar
Matt Tucker committed
1080
            oldAffiliation = MUCRole.Affiliation.outcast;
Matt Tucker's avatar
Matt Tucker committed
1081 1082 1083 1084 1085 1086
        }
        // Update the DB if the room is persistent
        MUCPersistenceManager.saveAffiliationToDB(
            this,
            bareJID,
            nickname,
Matt Tucker's avatar
Matt Tucker committed
1087
            MUCRole.Affiliation.member,
Matt Tucker's avatar
Matt Tucker committed
1088 1089 1090
            oldAffiliation);
        // Update the presence with the new affiliation and inform all occupants
        try {
Matt Tucker's avatar
Matt Tucker committed
1091 1092
            return changeOccupantAffiliation(bareJID, MUCRole.Affiliation.member,
                    MUCRole.Role.participant);
Matt Tucker's avatar
Matt Tucker committed
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
        }
        catch (NotAllowedException e) {
            // We should never receive this exception....in theory
            return null;
        }
    }

    private boolean removeMember(String bareJID) {
        boolean answer = members.containsKey(bareJID);
        members.remove(bareJID);
        return answer;
    }

1106
    public List<Presence> addOutcast(String bareJID, String reason, MUCRole senderRole)
Matt Tucker's avatar
Matt Tucker committed
1107
            throws NotAllowedException, ForbiddenException, ConflictException {
Matt Tucker's avatar
Matt Tucker committed
1108 1109 1110
        MUCRole.Affiliation oldAffiliation = MUCRole.Affiliation.none;
        if (MUCRole.Affiliation.admin != senderRole.getAffiliation()
                && MUCRole.Affiliation.owner != senderRole.getAffiliation()) {
Matt Tucker's avatar
Matt Tucker committed
1111 1112 1113 1114 1115 1116 1117
            throw new ForbiddenException();
        }
        // Check that the room always has an owner
        if (owners.contains(bareJID) && owners.size() == 1) {
            throw new ConflictException();
        }
        // Update the presence with the new affiliation and inform all occupants
1118
        JID actorJID = null;
1119 1120
        // actorJID will be null if the room itself (ie. via admin console) made the request
        if (senderRole.getChatUser() != null) {
1121
            actorJID = senderRole.getChatUser().getAddress();
1122
        }
1123
        List<Presence> updatedPresences = changeOccupantAffiliation(
Matt Tucker's avatar
Matt Tucker committed
1124
                bareJID,
Matt Tucker's avatar
Matt Tucker committed
1125 1126
                MUCRole.Affiliation.outcast,
                MUCRole.Role.none);
Gaston Dombiak's avatar
Gaston Dombiak committed
1127 1128 1129 1130 1131 1132 1133 1134 1135 1136
        Element frag;
        // Add the status code and reason why the user was banned to the presences that will
        // be sent to the room occupants (the banned user will not receive this presences)
        for (Presence presence : updatedPresences) {
            frag = presence.getChildElement("x", "http://jabber.org/protocol/muc#user");
            // Add the status code 301 that indicates that the user was banned
            frag.addElement("status").addAttribute("code", "301");
            // Add the reason why the user was banned
            if (reason != null && reason.trim().length() > 0) {
                frag.element("item").addElement("reason").setText(reason);
Matt Tucker's avatar
Matt Tucker committed
1137
            }
Gaston Dombiak's avatar
Gaston Dombiak committed
1138 1139 1140 1141 1142

            // Remove the banned users from the room. If a user has joined the room from
            // different client resources, he/she will be kicked from all the client resources
            // Effectively kick the occupant from the room
            kickPresence(presence, actorJID);
Matt Tucker's avatar
Matt Tucker committed
1143 1144 1145 1146 1147
        }
        // Update the affiliation lists
        outcasts.add(bareJID);
        // Remove the user from other affiliation lists
        if (removeOwner(bareJID)) {
Matt Tucker's avatar
Matt Tucker committed
1148
            oldAffiliation = MUCRole.Affiliation.owner;
Matt Tucker's avatar
Matt Tucker committed
1149 1150
        }
        else if (removeAdmin(bareJID)) {
Matt Tucker's avatar
Matt Tucker committed
1151
            oldAffiliation = MUCRole.Affiliation.admin;
Matt Tucker's avatar
Matt Tucker committed
1152 1153
        }
        else if (removeMember(bareJID)) {
Matt Tucker's avatar
Matt Tucker committed
1154
            oldAffiliation = MUCRole.Affiliation.member;
Matt Tucker's avatar
Matt Tucker committed
1155 1156 1157 1158 1159 1160
        }
        // Update the DB if the room is persistent
        MUCPersistenceManager.saveAffiliationToDB(
            this,
            bareJID,
            null,
Matt Tucker's avatar
Matt Tucker committed
1161
            MUCRole.Affiliation.outcast,
Matt Tucker's avatar
Matt Tucker committed
1162 1163 1164 1165 1166 1167 1168 1169
            oldAffiliation);
        return updatedPresences;
    }

    private boolean removeOutcast(String bareJID) {
        return outcasts.remove(bareJID);
    }

1170
    public List<Presence> addNone(String bareJID, MUCRole senderRole) throws ForbiddenException,
Matt Tucker's avatar
Matt Tucker committed
1171
            ConflictException {
Matt Tucker's avatar
Matt Tucker committed
1172 1173 1174
        MUCRole.Affiliation oldAffiliation = MUCRole.Affiliation.none;
        if (MUCRole.Affiliation.admin != senderRole.getAffiliation()
                && MUCRole.Affiliation.owner != senderRole.getAffiliation()) {
Matt Tucker's avatar
Matt Tucker committed
1175 1176 1177 1178 1179 1180
            throw new ForbiddenException();
        }
        // Check that the room always has an owner
        if (owners.contains(bareJID) && owners.size() == 1) {
            throw new ConflictException();
        }
1181
        List<Presence> updatedPresences = null;
1182 1183
        boolean wasMember = members.containsKey(bareJID) || admins.contains(bareJID) ||
                owners.contains(bareJID);
Matt Tucker's avatar
Matt Tucker committed
1184 1185
        // Remove the user from ALL the affiliation lists
        if (removeOwner(bareJID)) {
Matt Tucker's avatar
Matt Tucker committed
1186
            oldAffiliation = MUCRole.Affiliation.owner;
Matt Tucker's avatar
Matt Tucker committed
1187 1188
        }
        else if (removeAdmin(bareJID)) {
Matt Tucker's avatar
Matt Tucker committed
1189
            oldAffiliation = MUCRole.Affiliation.admin;
Matt Tucker's avatar
Matt Tucker committed
1190 1191
        }
        else if (removeMember(bareJID)) {
Matt Tucker's avatar
Matt Tucker committed
1192
            oldAffiliation = MUCRole.Affiliation.member;
Matt Tucker's avatar
Matt Tucker committed
1193 1194
        }
        else if (removeOutcast(bareJID)) {
Matt Tucker's avatar
Matt Tucker committed
1195
            oldAffiliation = MUCRole.Affiliation.outcast;
Matt Tucker's avatar
Matt Tucker committed
1196 1197 1198 1199 1200 1201
        }
        // Remove the affiliation of this user from the DB if the room is persistent
        MUCPersistenceManager.removeAffiliationFromDB(this, bareJID, oldAffiliation);

        // Update the presence with the new affiliation and inform all occupants
        try {
Matt Tucker's avatar
Matt Tucker committed
1202
            MUCRole.Role newRole;
1203
            if (isMembersOnly() && wasMember) {
Matt Tucker's avatar
Matt Tucker committed
1204
                newRole = MUCRole.Role.none;
Matt Tucker's avatar
Matt Tucker committed
1205 1206
            }
            else {
Matt Tucker's avatar
Matt Tucker committed
1207
                newRole = isModerated() ? MUCRole.Role.visitor : MUCRole.Role.participant;
Matt Tucker's avatar
Matt Tucker committed
1208
            }
Matt Tucker's avatar
Matt Tucker committed
1209
            updatedPresences = changeOccupantAffiliation(bareJID, MUCRole.Affiliation.none, newRole);
1210
            if (isMembersOnly() && wasMember) {
Matt Tucker's avatar
Matt Tucker committed
1211 1212 1213
                // If the room is members-only, remove the user from the room including a status
                // code of 321 to indicate that the user was removed because of an affiliation
                // change
1214
                Element frag;
Matt Tucker's avatar
Matt Tucker committed
1215
                // Add the status code to the presences that will be sent to the room occupants
Gaston Dombiak's avatar
Gaston Dombiak committed
1216
                for (Presence presence : updatedPresences) {
Matt Tucker's avatar
Matt Tucker committed
1217
                    // Set the presence as an unavailable presence
1218
                    presence.setType(Presence.Type.unavailable);
1219
                    presence.setStatus(null);
1220
                    frag = presence.getChildElement("x", "http://jabber.org/protocol/muc#user");
Matt Tucker's avatar
Matt Tucker committed
1221 1222
                    // Add the status code 321 that indicates that the user was removed because of
                    // an affiliation change
Gaston Dombiak's avatar
Gaston Dombiak committed
1223
                    frag.addElement("status").addAttribute("code", "321");
Matt Tucker's avatar
Matt Tucker committed
1224 1225 1226 1227 1228

                    // Remove the ex-member from the room. If a user has joined the room from
                    // different client resources, he/she will be kicked from all the client
                    // resources.
                    // Effectively kick the occupant from the room
1229
                    MUCUser senderUser = senderRole.getChatUser();
Gaston Dombiak's avatar
Gaston Dombiak committed
1230
                    JID actorJID = (senderUser == null ? null : senderUser.getAddress());
Matt Tucker's avatar
Matt Tucker committed
1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241
                    kickPresence(presence, actorJID);
                }
            }
        }
        catch (NotAllowedException e) {
            // We should never receive this exception....in theory
        }
        return updatedPresences;
    }

    public boolean isLocked() {
1242 1243 1244 1245 1246
        return lockedTime > 0;
    }

    public boolean isManuallyLocked() {
        return lockedTime > 0 && creationDate.getTime() != lockedTime;
Matt Tucker's avatar
Matt Tucker committed
1247 1248 1249
    }

    public void nicknameChanged(String oldNick, String newNick) {
1250
        // Associate the existing MUCRole with the new nickname
1251 1252 1253 1254 1255 1256 1257
        MUCRole occupant = occupants.get(oldNick.toLowerCase());
        // Check that we still have an occupant for the old nickname
        if (occupant != null) {
            occupants.put(newNick.toLowerCase(), occupant);
            // Remove the old nickname
            occupants.remove(oldNick.toLowerCase());
        }
Matt Tucker's avatar
Matt Tucker committed
1258 1259
    }

1260
    public void changeSubject(Message packet, MUCRole role) throws ForbiddenException {
Matt Tucker's avatar
Matt Tucker committed
1261 1262
        if ((canOccupantsChangeSubject() && role.getRole().compareTo(MUCRole.Role.visitor) < 0) ||
                MUCRole.Role.moderator == role.getRole()) {
1263 1264 1265 1266
            // Do nothing if the new subject is the same as the existing one
            if (packet.getSubject().equals(subject)) {
                return;
            }
1267 1268
            // Set the new subject to the room
            subject = packet.getSubject();
1269
            MUCPersistenceManager.updateRoomSubject(this);
Matt Tucker's avatar
Matt Tucker committed
1270
            // Notify all the occupants that the subject has changed
1271
            packet.setFrom(role.getRoleAddress());
Matt Tucker's avatar
Matt Tucker committed
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286
            send(packet);
        }
        else {
            throw new ForbiddenException();
        }
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

1287
    public void sendInvitation(JID to, String reason, MUCRole senderRole, List<Element> extensions)
Matt Tucker's avatar
Matt Tucker committed
1288
            throws ForbiddenException {
1289
        if (!isMembersOnly() || canOccupantsInvite()
Matt Tucker's avatar
Matt Tucker committed
1290 1291
                || MUCRole.Affiliation.admin == senderRole.getAffiliation()
                || MUCRole.Affiliation.owner == senderRole.getAffiliation()) {
Matt Tucker's avatar
Matt Tucker committed
1292 1293
            // If the room is not members-only OR if the room is members-only and anyone can send
            // invitations or the sender is an admin or an owner, then send the invitation
1294 1295 1296
            Message message = new Message();
            message.setFrom(role.getRoleAddress());
            message.setTo(to);
1297 1298 1299 1300 1301 1302 1303
            // Add a list of extensions sent with the original message invitation (if any)
            if (extensions != null) {
                for(Element element : extensions) {
                    element.setParent(null);
                    message.getElement().add(element);
                }
            }
1304
            Element frag = message.addChildElement("x", "http://jabber.org/protocol/muc#user");
1305 1306
            // ChatUser will be null if the room itself (ie. via admin console) made the request
            if (senderRole.getChatUser() != null) {
1307 1308
                frag.addElement("invite").addAttribute("from", senderRole.getChatUser().getAddress()
                        .toBareJID());
1309
            }
Matt Tucker's avatar
Matt Tucker committed
1310
            if (reason != null && reason.length() > 0) {
1311 1312 1313 1314 1315
                Element invite = frag.element("invite");
                if (invite == null) {
                    invite.addElement("invite");
                }
                invite.addElement("reason").setText(reason);
Matt Tucker's avatar
Matt Tucker committed
1316 1317
            }
            if (isPasswordProtected()) {
1318
                frag.addElement("password").setText(getPassword());
Matt Tucker's avatar
Matt Tucker committed
1319 1320 1321
            }

            // Include the jabber:x:conference information for backward compatibility
1322 1323
            frag = message.addChildElement("x", "jabber:x:conference");
            frag.addAttribute("jid", role.getRoleAddress().toBareJID());
Matt Tucker's avatar
Matt Tucker committed
1324 1325 1326 1327 1328 1329 1330 1331 1332

            // Send the message with the invitation
            router.route(message);
        }
        else {
            throw new ForbiddenException();
        }
    }

1333 1334 1335 1336 1337 1338
    public void sendInvitationRejection(JID to, String reason, JID sender) {
        Message message = new Message();
        message.setFrom(role.getRoleAddress());
        message.setTo(to);
        Element frag = message.addChildElement("x", "http://jabber.org/protocol/muc#user");
        frag.addElement("decline").addAttribute("from", sender.toBareJID());
Matt Tucker's avatar
Matt Tucker committed
1339
        if (reason != null && reason.length() > 0) {
1340
            frag.element("decline").addElement("reason").setText(reason);
Matt Tucker's avatar
Matt Tucker committed
1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354
        }

        // Send the message with the invitation
        router.route(message);
    }

    public IQOwnerHandler getIQOwnerHandler() {
        return iqOwnerHandler;
    }

    public IQAdminHandler getIQAdminHandler() {
        return iqAdminHandler;
    }

1355 1356 1357 1358
    public MUCRoomHistory getRoomHistory() {
        return roomHistory;
    }

1359 1360
    public Collection<String> getOwners() {
        return Collections.unmodifiableList(owners);
Matt Tucker's avatar
Matt Tucker committed
1361 1362
    }

1363 1364
    public Collection<String> getAdmins() {
        return Collections.unmodifiableList(admins);
Matt Tucker's avatar
Matt Tucker committed
1365 1366
    }

1367 1368
    public Collection<String> getMembers() {
        return Collections.unmodifiableMap(members).keySet();
Matt Tucker's avatar
Matt Tucker committed
1369 1370
    }

1371 1372
    public Collection<String> getOutcasts() {
        return Collections.unmodifiableList(outcasts);
Matt Tucker's avatar
Matt Tucker committed
1373 1374
    }

1375
    public Collection<MUCRole> getModerators() {
1376 1377
        List<MUCRole> moderators = new ArrayList<MUCRole>();
        for (MUCRole role : occupants.values()) {
Matt Tucker's avatar
Matt Tucker committed
1378
            if (MUCRole.Role.moderator == role.getRole()) {
1379
                moderators.add(role);
Matt Tucker's avatar
Matt Tucker committed
1380 1381
            }
        }
1382
        return moderators;
Matt Tucker's avatar
Matt Tucker committed
1383 1384
    }

1385
    public Collection<MUCRole> getParticipants() {
1386 1387
        List<MUCRole> participants = new ArrayList<MUCRole>();
        for (MUCRole role : occupants.values()) {
Matt Tucker's avatar
Matt Tucker committed
1388
            if (MUCRole.Role.participant == role.getRole()) {
1389
                participants.add(role);
Matt Tucker's avatar
Matt Tucker committed
1390 1391
            }
        }
1392
        return participants;
Matt Tucker's avatar
Matt Tucker committed
1393 1394
    }

1395
    public Presence addModerator(JID jid, MUCRole senderRole) throws ForbiddenException {
Matt Tucker's avatar
Matt Tucker committed
1396 1397
        if (MUCRole.Affiliation.admin != senderRole.getAffiliation()
                && MUCRole.Affiliation.owner != senderRole.getAffiliation()) {
Matt Tucker's avatar
Matt Tucker committed
1398 1399 1400 1401
            throw new ForbiddenException();
        }
        // Update the presence with the new role and inform all occupants
        try {
Matt Tucker's avatar
Matt Tucker committed
1402
            return changeOccupantRole(jid, MUCRole.Role.moderator);
Matt Tucker's avatar
Matt Tucker committed
1403 1404 1405 1406 1407 1408 1409
        }
        catch (NotAllowedException e) {
            // We should never receive this exception....in theory
            return null;
        }
    }

1410
    public Presence addParticipant(JID jid, String reason, MUCRole senderRole)
Matt Tucker's avatar
Matt Tucker committed
1411
            throws NotAllowedException, ForbiddenException {
Matt Tucker's avatar
Matt Tucker committed
1412
        if (MUCRole.Role.moderator != senderRole.getRole()) {
Matt Tucker's avatar
Matt Tucker committed
1413 1414 1415
            throw new ForbiddenException();
        }
        // Update the presence with the new role and inform all occupants
Matt Tucker's avatar
Matt Tucker committed
1416
        Presence updatedPresence = changeOccupantRole(jid, MUCRole.Role.participant);
Matt Tucker's avatar
Matt Tucker committed
1417
        if (updatedPresence != null) {
1418 1419
            Element frag = updatedPresence.getChildElement(
                    "x", "http://jabber.org/protocol/muc#user");
Matt Tucker's avatar
Matt Tucker committed
1420 1421
            // Add the reason why the user was granted voice
            if (reason != null && reason.trim().length() > 0) {
Gaston Dombiak's avatar
Gaston Dombiak committed
1422
                frag.element("item").addElement("reason").setText(reason);
Matt Tucker's avatar
Matt Tucker committed
1423 1424 1425 1426 1427
            }
        }
        return updatedPresence;
    }

1428
    public Presence addVisitor(JID jid, MUCRole senderRole) throws NotAllowedException,
Matt Tucker's avatar
Matt Tucker committed
1429
            ForbiddenException {
Matt Tucker's avatar
Matt Tucker committed
1430
        if (MUCRole.Role.moderator != senderRole.getRole()) {
Matt Tucker's avatar
Matt Tucker committed
1431 1432
            throw new ForbiddenException();
        }
Matt Tucker's avatar
Matt Tucker committed
1433
        return changeOccupantRole(jid, MUCRole.Role.visitor);
Matt Tucker's avatar
Matt Tucker committed
1434 1435
    }

1436
    public Presence kickOccupant(JID jid, JID actorJID, String reason)
Matt Tucker's avatar
Matt Tucker committed
1437 1438
            throws NotAllowedException {
        // Update the presence with the new role and inform all occupants
Matt Tucker's avatar
Matt Tucker committed
1439
        Presence updatedPresence = changeOccupantRole(jid, MUCRole.Role.none);
Matt Tucker's avatar
Matt Tucker committed
1440
        if (updatedPresence != null) {
1441 1442
            Element frag = updatedPresence.getChildElement(
                    "x", "http://jabber.org/protocol/muc#user");
Matt Tucker's avatar
Matt Tucker committed
1443 1444

            // Add the status code 307 that indicates that the user was kicked
Gaston Dombiak's avatar
Gaston Dombiak committed
1445
            frag.addElement("status").addAttribute("code", "307");
Matt Tucker's avatar
Matt Tucker committed
1446 1447
            // Add the reason why the user was kicked
            if (reason != null && reason.trim().length() > 0) {
Gaston Dombiak's avatar
Gaston Dombiak committed
1448
                frag.element("item").addElement("reason").setText(reason);
Matt Tucker's avatar
Matt Tucker committed
1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462
            }

            // Effectively kick the occupant from the room
            kickPresence(updatedPresence, actorJID);
        }
        return updatedPresence;
    }

    /**
     * Kicks the occupant from the room. This means that the occupant will receive an unavailable
     * presence with the actor that initiated the kick (if any). The occupant will also be removed
     * from the occupants lists.
     * 
     * @param kickPresence the presence of the occupant to kick from the room.
1463 1464
     * @param actorJID The JID of the actor that initiated the kick or <tt>null</tt> if the info
     * was not provided.
Matt Tucker's avatar
Matt Tucker committed
1465
     */
1466
    private void kickPresence(Presence kickPresence, JID actorJID) {
Matt Tucker's avatar
Matt Tucker committed
1467 1468
        MUCRole kickedRole;
        // Get the role to kick
1469
        kickedRole = occupants.get(kickPresence.getFrom().getResource());
Matt Tucker's avatar
Matt Tucker committed
1470
        if (kickedRole != null) {
1471
            kickPresence = kickPresence.createCopy();
1472
            // Add the actor's JID that kicked this user from the room
1473 1474 1475
            if (actorJID != null && actorJID.toString().length() > 0) {
                Element frag = kickPresence.getChildElement(
                        "x", "http://jabber.org/protocol/muc#user");
Gaston Dombiak's avatar
Gaston Dombiak committed
1476
                frag.element("item").addElement("actor").addAttribute("jid", actorJID.toBareJID());
Matt Tucker's avatar
Matt Tucker committed
1477
            }
1478 1479
            // Send the unavailable presence to the banned user
            kickedRole.send(kickPresence);
Matt Tucker's avatar
Matt Tucker committed
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508
            // Remove the occupant from the room's occupants lists
            removeOccupantRole(kickedRole);
        }
    }

    public boolean canAnyoneDiscoverJID() {
        return canAnyoneDiscoverJID;
    }

    public void setCanAnyoneDiscoverJID(boolean canAnyoneDiscoverJID) {
        this.canAnyoneDiscoverJID = canAnyoneDiscoverJID;
    }

    public boolean canOccupantsChangeSubject() {
        return canOccupantsChangeSubject;
    }

    public void setCanOccupantsChangeSubject(boolean canOccupantsChangeSubject) {
        this.canOccupantsChangeSubject = canOccupantsChangeSubject;
    }

    public boolean canOccupantsInvite() {
        return canOccupantsInvite;
    }

    public void setCanOccupantsInvite(boolean canOccupantsInvite) {
        this.canOccupantsInvite = canOccupantsInvite;
    }

1509 1510 1511 1512 1513 1514 1515 1516
    public String getNaturalLanguageName() {
        return naturalLanguageName;
    }

    public void setNaturalLanguageName(String naturalLanguageName) {
        this.naturalLanguageName = naturalLanguageName;
    }

Matt Tucker's avatar
Matt Tucker committed
1517 1518 1519 1520 1521 1522 1523 1524
    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

1525 1526
    public boolean isMembersOnly() {
        return membersOnly;
Matt Tucker's avatar
Matt Tucker committed
1527 1528
    }

1529
    public List<Presence> setMembersOnly(boolean membersOnly) {
1530
        List<Presence> presences = new ArrayList<Presence>();
1531
        if (membersOnly && !this.membersOnly) {
1532 1533 1534
            // If the room was not members-only and now it is, kick occupants that aren't member
            // of the room
            for (MUCRole occupant : occupants.values()) {
Matt Tucker's avatar
Matt Tucker committed
1535
                if (occupant.getAffiliation().compareTo(MUCRole.Affiliation.member) > 0) {
Derek DeMoro's avatar
Derek DeMoro committed
1536 1537 1538 1539 1540
                    try {
                        presences.add(kickOccupant(occupant.getRoleAddress(), null,
                                LocaleUtils.getLocalizedString("muc.roomIsNowMembersOnly")));
                    }
                    catch (NotAllowedException e) {
1541
                        Log.error(e);
Derek DeMoro's avatar
Derek DeMoro committed
1542
                    }
1543 1544 1545
                }
            }
        }
1546
        this.membersOnly = membersOnly;
1547
        return presences;
Matt Tucker's avatar
Matt Tucker committed
1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582
    }

    public boolean isLogEnabled() {
        return logEnabled;
    }

    public void setLogEnabled(boolean logEnabled) {
        this.logEnabled = logEnabled;
    }

    public int getMaxUsers() {
        return maxUsers;
    }

    public void setMaxUsers(int maxUsers) {
        this.maxUsers = maxUsers;
    }

    public boolean isModerated() {
        return moderated;
    }

    public void setModerated(boolean moderated) {
        this.moderated = moderated;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public boolean isPasswordProtected() {
1583
        return password != null && password.trim().length() > 0;
Matt Tucker's avatar
Matt Tucker committed
1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605
    }

    public boolean isPersistent() {
        return persistent;
    }

    public boolean wasSavedToDB() {
        if (!isPersistent()) {
            return false;
        }
        return savedToDB;
    }
    
    public void setSavedToDB(boolean saved) {
        this.savedToDB = saved;
    }
    
    public void setPersistent(boolean persistent) {
        this.persistent = persistent;
    }

    public boolean isPublicRoom() {
1606
        return !isDestroyed && publicRoom;
Matt Tucker's avatar
Matt Tucker committed
1607 1608 1609 1610 1611 1612
    }

    public void setPublicRoom(boolean publicRoom) {
        this.publicRoom = publicRoom;
    }

1613 1614
    public List<String> getRolesToBroadcastPresence() {
        return Collections.unmodifiableList(rolesToBroadcastPresence);
Matt Tucker's avatar
Matt Tucker committed
1615 1616
    }

1617
    public void setRolesToBroadcastPresence(List<String> rolesToBroadcastPresence) {
Matt Tucker's avatar
Matt Tucker committed
1618 1619 1620 1621 1622 1623 1624
        // TODO If the list changes while there are occupants in the room we must send available or
        // unavailable presences of the affected occupants to the rest of the occupants
        this.rolesToBroadcastPresence = rolesToBroadcastPresence;
    }

    /**
     * Returns true if we need to check whether a presence could be sent or not.
1625
     *
Matt Tucker's avatar
Matt Tucker committed
1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
     * @return true if we need to check whether a presence could be sent or not.
     */
    private boolean hasToCheckRoleToBroadcastPresence() {
        // For performance reasons the check is done based on the size of the collection.
        return rolesToBroadcastPresence.size() < 3;
    }

    public boolean canBroadcastPresence(String roleToBroadcast) {
        return "none".equals(roleToBroadcast) || rolesToBroadcastPresence.contains(roleToBroadcast);
    }

1637
    public void lock(MUCRole senderRole) throws ForbiddenException {
Matt Tucker's avatar
Matt Tucker committed
1638
        if (MUCRole.Affiliation.owner != senderRole.getAffiliation()) {
1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651
            throw new ForbiddenException();
        }
        if (isLocked()) {
            // Do nothing if the room was already locked
            return;
        }
        setLocked(true);
        if (senderRole.getChatUser() != null) {
            // Send to the occupant that locked the room a message saying so
            Message message = new Message();
            message.setType(Message.Type.groupchat);
            message.setBody(LocaleUtils.getLocalizedString("muc.locked"));
            message.setFrom(getRole().getRoleAddress());
1652
            senderRole.send(message);
1653 1654 1655 1656
        }
    }

    public void unlock(MUCRole senderRole) throws ForbiddenException {
Matt Tucker's avatar
Matt Tucker committed
1657
        if (MUCRole.Affiliation.owner != senderRole.getAffiliation()) {
1658 1659 1660 1661 1662 1663 1664
            throw new ForbiddenException();
        }
        if (!isLocked()) {
            // Do nothing if the room was already unlocked
            return;
        }
        setLocked(false);
1665 1666
        if (senderRole.getChatUser() != null) {
            // Send to the occupant that unlocked the room a message saying so
1667 1668
            Message message = new Message();
            message.setType(Message.Type.groupchat);
1669
            message.setBody(LocaleUtils.getLocalizedString("muc.unlocked"));
1670
            message.setFrom(getRole().getRoleAddress());
1671
            senderRole.send(message);
1672
        }
Matt Tucker's avatar
Matt Tucker committed
1673 1674
    }

1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708
    private void setLocked(boolean locked) {
        if (locked) {
            this.lockedTime = System.currentTimeMillis();
        }
        else {
            this.lockedTime = 0;
        }
        MUCPersistenceManager.updateRoomLock(this);
    }

    /**
     * Sets the date when the room was locked. Initially when the room is created it is locked so
     * the locked date is the creation date of the room. Afterwards, the room may be manually
     * locked and unlocked so the locked date may be in these cases different than the creation
     * date. A Date with time 0 means that the the room is unlocked.
     *
     * @param lockedTime the date when the room was locked.
     */
    void setLockedDate(Date lockedTime) {
        this.lockedTime = lockedTime.getTime();
    }

    /**
     * Returns the date when the room was locked. Initially when the room is created it is locked so
     * the locked date is the creation date of the room. Afterwards, the room may be manually
     * locked and unlocked so the locked date may be in these cases different than the creation
     * date. When the room is unlocked a Date with time 0 is returned.
     *
     * @return the date when the room was locked.
     */
    Date getLockedDate() {
        return new Date(lockedTime);
    }

1709 1710 1711 1712
    public List<Presence> addAdmins(List<String> newAdmins, MUCRole senderRole)
            throws ForbiddenException, ConflictException {
        List<Presence> answer = new ArrayList<Presence>(newAdmins.size());
        for (String newAdmin : newAdmins) {
Matt Tucker's avatar
Matt Tucker committed
1713 1714 1715 1716 1717 1718 1719
            if (newAdmin.trim().length() > 0 && !admins.contains(newAdmin)) {
                answer.addAll(addAdmin(newAdmin, senderRole));
            }
        }
        return answer;
    }

1720 1721 1722 1723
    public List<Presence> addOwners(List<String> newOwners, MUCRole senderRole)
            throws ForbiddenException {
        List<Presence> answer = new ArrayList<Presence>(newOwners.size());
        for (String newOwner : newOwners) {
Matt Tucker's avatar
Matt Tucker committed
1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737
            if (newOwner.trim().length() > 0 && !owners.contains(newOwner)) {
                answer.addAll(addOwner(newOwner, senderRole));
            }
        }
        return answer;
    }

    public void saveToDB() {
        // Make the room persistent
        MUCPersistenceManager.saveToDB(this);
        if (!savedToDB) {
            // Set that the room is now in the DB
            savedToDB = true;
            // Save the existing room owners to the DB
1738
            for (String owner : owners) {
Matt Tucker's avatar
Matt Tucker committed
1739 1740
                MUCPersistenceManager.saveAffiliationToDB(
                    this,
1741
                    owner,
Matt Tucker's avatar
Matt Tucker committed
1742
                    null,
Matt Tucker's avatar
Matt Tucker committed
1743 1744
                    MUCRole.Affiliation.owner,
                    MUCRole.Affiliation.none);
Matt Tucker's avatar
Matt Tucker committed
1745 1746
            }
            // Save the existing room admins to the DB
1747
            for (String admin : admins) {
Matt Tucker's avatar
Matt Tucker committed
1748 1749
                MUCPersistenceManager.saveAffiliationToDB(
                    this,
1750
                    admin,
Matt Tucker's avatar
Matt Tucker committed
1751
                    null,
Matt Tucker's avatar
Matt Tucker committed
1752 1753
                    MUCRole.Affiliation.admin,
                    MUCRole.Affiliation.none);
Matt Tucker's avatar
Matt Tucker committed
1754 1755 1756 1757 1758
            }
            // Save the existing room members to the DB
            for (Iterator it=members.keySet().iterator(); it.hasNext();) {
                String bareJID = (String)it.next();
                MUCPersistenceManager.saveAffiliationToDB(this, bareJID, (String) members
Matt Tucker's avatar
Matt Tucker committed
1759
                        .get(bareJID), MUCRole.Affiliation.member, MUCRole.Affiliation.none);
Matt Tucker's avatar
Matt Tucker committed
1760 1761
            }
            // Save the existing room outcasts to the DB
1762
            for (String outcast : outcasts) {
Matt Tucker's avatar
Matt Tucker committed
1763 1764
                MUCPersistenceManager.saveAffiliationToDB(
                    this,
1765
                    outcast,
Matt Tucker's avatar
Matt Tucker committed
1766
                    null,
Matt Tucker's avatar
Matt Tucker committed
1767 1768
                    MUCRole.Affiliation.outcast,
                    MUCRole.Affiliation.none);
Matt Tucker's avatar
Matt Tucker committed
1769 1770 1771 1772
            }
        }
    }
}