Ejemplo n.º 1
0
  public boolean isSessionValid(UserSession userSession, RequestContext request) {
    String remoteUser = null;

    Cookie SSOCookie = ControllerUtils.getCookie("JforumSSO"); // my app login cookie
    logger.info("DEBUG - CustomSSO - isSessionValid - Getting JForumSSO Cookie!");

    if (SSOCookie != null) remoteUser = SSOCookie.getValue(); //  jforum username

    if (remoteUser == null) {
      logger.info("DEBUG - CustomSSO - isSessionValid - JForumSSO Cookie is NULL!");
      JForumExecutionContext.setRedirect(SystemGlobals.getValue(ConfigKeys.SSO_REDIRECT));
      return false;

    } else if (remoteUser.equals("")) {
      logger.info("DEBUG - CustomSSO - isSessionValid - JForumSSO Cookie is empty!");
      JForumExecutionContext.setRedirect(SystemGlobals.getValue(ConfigKeys.SSO_REDIRECT));
      return false;
      // user has since logged in
    } else if (remoteUser != null
        && userSession.getUserId() == SystemGlobals.getIntValue(ConfigKeys.ANONYMOUS_USER_ID)) {
      logger.info("DEBUG - CustomSSO - isSessionValid - JForumSSO Cookie is Anonymous!");
      return false;
      // user has changed user
    } else if (remoteUser != null && !remoteUser.equals(userSession.getUsername())) {
      logger.info("DEBUG - CustomSSO - isSessionValid - JForumSSO Cookie User Mismatch");
      return false;
    }
    logger.info("DEBUG - CustomSSO - isSessionValid - Returning True");
    return true; // sso pool apps user and forum user the same
  }
Ejemplo n.º 2
0
  /**
   * Prepares the mail message for sending.
   *
   * @param subject the subject of the email
   * @param messageFile the path to the mail message template
   * @throws MailException
   */
  protected void prepareMessage(final String subject, final String messageFile)
      throws MailException {
    if (this.messageId != null) {
      this.message = new IdentifiableMimeMessage(session);
      ((IdentifiableMimeMessage) this.message).setMessageId(this.messageId);
    } else {
      this.message = new MimeMessage(session);
    }

    this.templateParams.put("forumName", SystemGlobals.getValue(ConfigKeys.FORUM_NAME));

    try {
      this.message.setSentDate(new Date());
      this.message.setFrom(new InternetAddress(SystemGlobals.getValue(ConfigKeys.MAIL_SENDER)));
      this.message.setSubject(subject, SystemGlobals.getValue(ConfigKeys.MAIL_CHARSET));

      if (this.inReplyTo != null) {
        this.message.addHeader("In-Reply-To", this.inReplyTo);
      }

      this.createTemplate(messageFile);
      this.needCustomization = this.isCustomizationNeeded();

      // If we don't need to customize any part of the message,
      // then build the generic text right now
      if (!this.needCustomization) {
        String text = this.processTemplate();
        this.defineMessageText(text);
      }
    } catch (Exception e) {
      throw new MailException(e);
    }
  }
Ejemplo n.º 3
0
  public String authenticateUser(RequestContext request) {
    Cookie cookie = ControllerUtils.getCookie("JForumSSO");
    logger.info("DEBUG - CustomSSO - authenticatUser - Getting JForumSSO Cookie!");

    String username = null;
    if (cookie == null) {
      logger.info("DEBUG - CustomSSO - authenticatUser - JForumSSO Cookie is NULL!");
      JForumExecutionContext.setRedirect(SystemGlobals.getValue(ConfigKeys.SSO_REDIRECT));

      return null;
    } else {
      username = (String) cookie.getValue();
      logger.info(
          "DEBUG - CustomSSO - authenticatUser - JForumSSO Cookie is contains username: "******"!");
      if (username.equals("")) {
        logger.info("DEBUG - CustomSSO - authenticatUser - JForumSSO Cookie is empty!");
        JForumExecutionContext.setRedirect(SystemGlobals.getValue(ConfigKeys.SSO_REDIRECT));
      }
    }
    logger.info(
        "DEBUG - CustomSSO - authenticatUser - JForumSSO is returning username: "******"!");
    return username;
  }
Ejemplo n.º 4
0
  private String getSql(String queryName) {
    String query = SystemGlobals.getSql(queryName);

    query =
        StringUtils.replace(query, "${phpbb}", SystemGlobals.getValue(ConfigKeys.DATABASE_PHPBB));
    query =
        StringUtils.replace(
            query, "${table.prefix}", SystemGlobals.getValue(ConfigKeys.PHPBB_TABLE_PREFIX));

    return query;
  }
Ejemplo n.º 5
0
  public void configurations() {
    this.context.put("icon", SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_ICON));
    this.context.put(
        "createThumb", SystemGlobals.getBoolValue(ConfigKeys.ATTACHMENTS_IMAGES_CREATE_THUMB));
    this.context.put("thumbH", SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_IMAGES_MAX_THUMB_H));
    this.context.put("thumbW", SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_IMAGES_MAX_THUMB_W));
    this.context.put("maxPost", SystemGlobals.getValue(ConfigKeys.ATTACHMENTS_MAX_POST));
    this.context.put(
        "thumbBorder", SystemGlobals.getBoolValue(ConfigKeys.ATTACHMENTS_IMAGES_THUMB_BOX_SHOW));

    this.setTemplateName(TemplateKeys.ATTACHMENTS_CONFIG);
  }
Ejemplo n.º 6
0
  /**
   * Checks user credentials / automatic login.
   *
   * @param userSession The UserSession instance associated to the user's session
   * @return <code>true</code> if auto login was enabled and the user was sucessfuly logged in.
   * @throws DatabaseException
   */
  protected boolean checkAutoLogin(UserSession userSession) {

    LOG.trace("checkAutoLogin");
    String cookieName = SystemGlobals.getValue(ConfigKeys.COOKIE_NAME_DATA);

    Cookie cookie = this.getCookieTemplate(cookieName);
    Cookie hashCookie = this.getCookieTemplate(SystemGlobals.getValue(ConfigKeys.COOKIE_USER_HASH));
    Cookie autoLoginCookie =
        this.getCookieTemplate(SystemGlobals.getValue(ConfigKeys.COOKIE_AUTO_LOGIN));

    if (hashCookie != null
        && cookie != null
        && !cookie.getValue().equals(SystemGlobals.getValue(ConfigKeys.ANONYMOUS_USER_ID))
        && autoLoginCookie != null
        && "1".equals(autoLoginCookie.getValue())) {
      String uid = cookie.getValue();
      String uidHash = hashCookie.getValue();

      // Load the user-specific security hash from the database
      try {
        UserDAO userDao = DataAccessDriver.getInstance().newUserDAO();
        String userHash = userDao.getUserAuthHash(Integer.parseInt(uid));

        if (userHash == null || userHash.trim().length() == 0) {
          return false;
        }

        String securityHash = MD5.crypt(userHash);

        if (securityHash.equals(uidHash)) {
          int userId = Integer.parseInt(uid);
          userSession.setUserId(userId);

          User user = userDao.selectById(userId);

          if (user == null || user.getId() != userId || user.isDeleted()) {
            userSession.makeAnonymous();
            return false;
          }

          this.configureUserSession(userSession, user);

          return true;
        }
      } catch (Exception e) {
        throw new DatabaseException(e);
      }

      userSession.makeAnonymous();
    }

    return false;
  }
Ejemplo n.º 7
0
  public void init(ServletConfig config) throws ServletException {
    super.init(config);

    try {
      String appPath = config.getServletContext().getRealPath("");
      // 是否为开发mode
      debug = "true".equals(config.getInitParameter("development"));
      // 读取log4j.xml配置文件
      DOMConfigurator.configure(appPath + "/WEB-INF/log4j.xml");

      logger.info("Starting JForum. Debug mode is " + debug);
      //
      ConfigLoader.startSystemglobals(appPath);
      // 启动缓存引擎
      ConfigLoader.startCacheEngine();

      // Configure the template engine
      Configuration templateCfg = new Configuration();
      templateCfg.setTemplateUpdateDelay(2);
      templateCfg.setSetting("number_format", "#");
      templateCfg.setSharedVariable("startupTime", new Long(new Date().getTime()));

      // Create the default template loader
      String defaultPath = SystemGlobals.getApplicationPath() + "/templates";
      FileTemplateLoader defaultLoader = new FileTemplateLoader(new File(defaultPath));

      String extraTemplatePath = SystemGlobals.getValue(ConfigKeys.FREEMARKER_EXTRA_TEMPLATE_PATH);

      if (StringUtils.isNotBlank(extraTemplatePath)) {
        // An extra template path is configured, we need a MultiTemplateLoader
        FileTemplateLoader extraLoader = new FileTemplateLoader(new File(extraTemplatePath));
        TemplateLoader[] loaders = new TemplateLoader[] {extraLoader, defaultLoader};
        MultiTemplateLoader multiLoader = new MultiTemplateLoader(loaders);
        templateCfg.setTemplateLoader(multiLoader);
      } else {
        // An extra template path is not configured, we only need the default loader
        templateCfg.setTemplateLoader(defaultLoader);
      }
      // 载入模块
      ModulesRepository.init(SystemGlobals.getValue(ConfigKeys.CONFIG_DIR));

      this.loadConfigStuff();

      if (!this.debug) {
        templateCfg.setTemplateUpdateDelay(3600);
      }

      JForumExecutionContext.setTemplateConfig(templateCfg);
    } catch (Exception e) {
      throw new ForumStartupException("Error while starting JForum", e);
    }
  }
Ejemplo n.º 8
0
  protected Spammer() throws MailException {
    final boolean ssl = SystemGlobals.getBoolValue(ConfigKeys.MAIL_SMTP_SSL);

    final String hostProperty = this.hostProperty(ssl);
    final String portProperty = this.portProperty(ssl);
    final String authProperty = this.authProperty(ssl);
    final String localhostProperty = this.localhostProperty(ssl);

    mailProps.put(hostProperty, SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_HOST));
    mailProps.put(portProperty, SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_PORT));

    String localhost = SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_LOCALHOST);

    if (StringUtils.isNotEmpty(localhost)) {
      LOGGER.debug("localhost=" + localhost);
      mailProps.put(localhostProperty, localhost);
    }

    mailProps.put("mail.mime.address.strict", "false");
    mailProps.put("mail.mime.charset", SystemGlobals.getValue(ConfigKeys.MAIL_CHARSET));
    mailProps.put(authProperty, SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_AUTH));

    username = SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_USERNAME);
    password = SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_PASSWORD);

    messageFormat =
        SystemGlobals.getValue(ConfigKeys.MAIL_MESSSAGE_FORMAT).equals("html")
            ? MESSAGE_HTML
            : MESSAGE_TEXT;

    this.session = Session.getInstance(mailProps);
  }
Ejemplo n.º 9
0
  private String applyRegexToPostText(String text) {
    for (int i = 0; i < this.regexps.length; i++) {
      if (text == null) {
        text = "";
      } else {
        text =
            text.replaceAll(
                SystemGlobals.getValue(this.regexps[i][0]),
                SystemGlobals.getValue(this.regexps[i][1]));
      }
    }

    return text;
  }
Ejemplo n.º 10
0
  /**
   * Gets the registration date of the user
   *
   * @return String value with the registration date
   */
  public String getRegistrationDate() {

    LOG.trace("getRegistrationDate");
    SimpleDateFormat df = new SimpleDateFormat(SystemGlobals.getValue(ConfigKeys.DATE_TIME_FORMAT));

    return df.format(this.registrationDate);
  }
Ejemplo n.º 11
0
  protected Post makePost(ResultSet rs) throws SQLException {
    Post post = new Post();
    post.setId(rs.getInt("post_id"));
    post.setTopicId(rs.getInt("topic_id"));
    post.setForumId(rs.getInt("forum_id"));
    post.setUserId(rs.getInt("user_id"));

    Timestamp postTime = rs.getTimestamp("post_time");
    post.setTime(new Date(postTime.getTime()));
    post.setUserIp(rs.getString("poster_ip"));
    post.setBbCodeEnabled(rs.getInt("enable_bbcode") > 0);
    post.setHtmlEnabled(rs.getInt("enable_html") > 0);
    post.setSmiliesEnabled(rs.getInt("enable_smilies") > 0);
    post.setSignatureEnabled(rs.getInt("enable_sig") > 0);
    post.setEditCount(rs.getInt("post_edit_count"));

    Timestamp editTime = rs.getTimestamp("post_edit_time");
    post.setEditTime(editTime != null ? new Date(editTime.getTime()) : null);

    post.setSubject(rs.getString("post_subject"));
    post.setText(this.getPostTextFromResultSet(rs));
    post.setPostUsername(rs.getString("username"));
    post.hasAttachments(rs.getInt("attach") > 0);
    post.setModerate(rs.getInt("need_moderate") == 1);

    SimpleDateFormat df = new SimpleDateFormat(SystemGlobals.getValue(ConfigKeys.DATE_TIME_FORMAT));
    post.setFormatedTime(df.format(postTime));

    post.setKarma(DataAccessDriver.getInstance().newKarmaDAO().getPostKarma(post.getId()));

    return post;
  }
Ejemplo n.º 12
0
  /**
   * Do a refresh in the user's session. This method will update the last visit time for the current
   * user, as well checking for authentication if the session is new or the SSO user has changed
   */
  public void refreshSession() {

    LOG.trace("refreshSession");
    UserSession userSession = SessionFacade.getUserSession();
    RequestContext request = JForumExecutionContext.getRequest();

    if (userSession == null) {
      userSession = new UserSession();
      userSession.registerBasicInfo();
      userSession.setSessionId(request.getSessionContext().getId());
      userSession.setIp(request.getRemoteAddr());
      SessionFacade.makeUnlogged();

      if (!JForumExecutionContext.getForumContext().isBot()) {
        // Non-SSO authentications can use auto login
        if (!ConfigKeys.TYPE_SSO.equals(SystemGlobals.getValue(ConfigKeys.AUTHENTICATION_TYPE))) {
          if (SystemGlobals.getBoolValue(ConfigKeys.AUTO_LOGIN_ENABLED)) {
            this.checkAutoLogin(userSession);
          } else {
            userSession.makeAnonymous();
          }
        } else {
          this.checkSSO(userSession);
        }
      }

      SessionFacade.add(userSession);
    } else if (ConfigKeys.TYPE_SSO.equals(SystemGlobals.getValue(ConfigKeys.AUTHENTICATION_TYPE))) {
      SSO sso;

      try {
        sso =
            (SSO)
                Class.forName(SystemGlobals.getValue(ConfigKeys.SSO_IMPLEMENTATION)).newInstance();
      } catch (Exception e) {
        throw new ForumException(e);
      }

      // If SSO, then check if the session is valid
      if (!sso.isSessionValid(userSession, request)) {
        SessionFacade.remove(userSession.getSessionId());
        refreshSession();
      }
    } else {
      SessionFacade.getUserSession().updateSessionTime();
    }
  }
Ejemplo n.º 13
0
  protected void loadConfigStuff() {
    ConfigLoader.loadUrlPatterns();
    I18n.load();
    Tpl.load(SystemGlobals.getValue(ConfigKeys.TEMPLATES_MAPPING));

    // BB Code
    BBCodeRepository.setBBCollection(new BBCodeHandler().parse());
  }
Ejemplo n.º 14
0
  protected void startApplication() {
    try {
      SystemGlobals.loadQueries(SystemGlobals.getValue(ConfigKeys.SQL_QUERIES_GENERIC));
      SystemGlobals.loadQueries(SystemGlobals.getValue(ConfigKeys.SQL_QUERIES_DRIVER));

      String filename = SystemGlobals.getValue(ConfigKeys.QUARTZ_CONFIG);
      SystemGlobals.loadAdditionalDefaults(filename);

      ConfigLoader.createLoginAuthenticator();
      ConfigLoader.loadDaoImplementation();
      ConfigLoader.listenForChanges();
      //			ConfigLoader.startSearchIndexer();
      ConfigLoader.startSummaryJob();
    } catch (Exception e) {
      throw new ForumStartupException("Error while starting JForum", e);
    }
  }
Ejemplo n.º 15
0
  /** Load the default I18n file */
  public static synchronized void load() {
    baseDir =
        SystemGlobals.getApplicationResourceDir()
            + "/"
            + SystemGlobals.getValue(ConfigKeys.LOCALES_DIR);

    loadLocales();

    defaultName = SystemGlobals.getValue(ConfigKeys.I18N_DEFAULT_ADMIN);
    load(defaultName, null);

    String custom = SystemGlobals.getValue(ConfigKeys.I18N_DEFAULT);
    if (!custom.equals(defaultName)) {
      load(custom, defaultName);
      defaultName = custom;
    }
  }
Ejemplo n.º 16
0
  /**
   * Set the text contents of the email we're sending
   *
   * @param text the text to set
   * @throws MessagingException
   */
  private void defineMessageText(final String text) throws MessagingException {
    String charset = SystemGlobals.getValue(ConfigKeys.MAIL_CHARSET);

    if (messageFormat == MESSAGE_HTML) {
      this.message.setContent(text.replaceAll("\n", "<br>"), "text/html; charset=" + charset);
    } else {
      this.message.setText(text);
    }
  }
Ejemplo n.º 17
0
  /**
   * Gets the message text to send in the email.
   *
   * @param messageFile The optional message file to load the text.
   * @throws Exception
   */
  protected void createTemplate(final String messageFile) throws IOException {
    String templateEncoding = SystemGlobals.getValue(ConfigKeys.MAIL_TEMPLATE_ENCODING);

    if (StringUtils.isEmpty(templateEncoding)) {
      this.template = JForumExecutionContext.getTemplateConfig().getTemplate(messageFile);
    } else {
      this.template =
          JForumExecutionContext.getTemplateConfig().getTemplate(messageFile, templateEncoding);
    }
  }
Ejemplo n.º 18
0
  /**
   * @see net.jforum.sso.LoginAuthenticator#validateLogin(java.lang.String, java.lang.String,
   *     java.util.Map)
   */
  public User validateLogin(String username, String password, Map extraParams) {
    Hashtable environment = this.prepareEnvironment();

    StringBuffer principal =
        new StringBuffer(256)
            .append(SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_PREFIX))
            .append(username)
            .append(',')
            .append(SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_SUFFIX));

    environment.put(Context.SECURITY_PRINCIPAL, principal.toString());
    environment.put(Context.SECURITY_CREDENTIALS, password);

    DirContext dir = null;

    try {
      dir = new InitialDirContext(environment);

      String lookupPrefix = SystemGlobals.getValue(ConfigKeys.LDAP_LOOKUP_PREFIX);
      String lookupSuffix = SystemGlobals.getValue(ConfigKeys.LDAP_LOOKUP_SUFFIX);

      if (lookupPrefix == null || lookupPrefix.length() == 0) {
        lookupPrefix = SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_PREFIX);
      }

      if (lookupSuffix == null || lookupSuffix.length() == 0) {
        lookupSuffix = SystemGlobals.getValue(ConfigKeys.LDAP_LOGIN_SUFFIX);
      }

      String lookupPrincipal = lookupPrefix + username + "," + lookupSuffix;

      Attribute att =
          dir.getAttributes(lookupPrincipal)
              .get(SystemGlobals.getValue(ConfigKeys.LDAP_FIELD_EMAIL));

      SSOUtils utils = new SSOUtils();

      if (!utils.userExists(username)) {
        String email = att != null ? (String) att.get() : "noemail";
        utils.register("ldap", email);
      }

      return utils.getUser();
    } catch (AuthenticationException e) {
      return null;
    } catch (NamingException e) {
      return null;
    } finally {
      if (dir != null) {
        try {
          dir.close();
        } catch (NamingException e) {
          // close jndi context
        }
      }
    }
  }
Ejemplo n.º 19
0
  private Hashtable prepareEnvironment() {
    Hashtable h = new Hashtable();

    h.put(Context.INITIAL_CONTEXT_FACTORY, SystemGlobals.getValue(ConfigKeys.LDAP_FACTORY));
    h.put(Context.PROVIDER_URL, SystemGlobals.getValue(ConfigKeys.LDAP_SERVER_URL));

    String protocol = SystemGlobals.getValue(ConfigKeys.LDAP_SECURITY_PROTOCOL);

    if (protocol != null && !"".equals(protocol.trim())) {
      h.put(Context.SECURITY_PROTOCOL, protocol);
    }

    String authentication = SystemGlobals.getValue(ConfigKeys.LDAP_AUTHENTICATION);

    if (authentication != null && !"".equals(authentication.trim())) {
      h.put(Context.SECURITY_AUTHENTICATION, authentication);
    }

    return h;
  }
Ejemplo n.º 20
0
  /**
   * Checks for user authentication using some SSO implementation
   *
   * @param userSession UserSession
   */
  protected void checkSSO(UserSession userSession) {

    LOG.trace("checkSSO");
    try {
      SSO sso =
          (SSO) Class.forName(SystemGlobals.getValue(ConfigKeys.SSO_IMPLEMENTATION)).newInstance();
      String username = sso.authenticateUser(JForumExecutionContext.getRequest());

      if (username == null || username.trim().equals("")) {
        userSession.makeAnonymous();
      } else {
        SSOUtils utils = new SSOUtils();

        if (!utils.userExists(username)) {
          SessionContext session = JForumExecutionContext.getRequest().getSessionContext();

          String email =
              (String) session.getAttribute(SystemGlobals.getValue(ConfigKeys.SSO_EMAIL_ATTRIBUTE));
          String password =
              (String)
                  session.getAttribute(SystemGlobals.getValue(ConfigKeys.SSO_PASSWORD_ATTRIBUTE));

          if (email == null) {
            email = SystemGlobals.getValue(ConfigKeys.SSO_DEFAULT_EMAIL);
          }

          if (password == null) {
            password = SystemGlobals.getValue(ConfigKeys.SSO_DEFAULT_PASSWORD);
          }

          utils.register(password, email);
        }

        this.configureUserSession(userSession, utils.getUser());
      }
    } catch (Exception e) {
      e.printStackTrace();
      throw new ForumException("Error while executing SSO actions: " + e);
    }
  }
Ejemplo n.º 21
0
  private static void splitAndTrim(String s, Set<String> data) {
    String value = SystemGlobals.getValue(s);

    if (value == null) {
      return;
    }

    String[] tags = value.toUpperCase().split(",");

    for (int i = 0; i < tags.length; i++) {
      data.add(tags[i].trim());
    }
  }
Ejemplo n.º 22
0
  static void load(String localeName, String mergeWith, boolean force) {
    if (!force
        && (localeName == null || localeName.trim().equals("") || I18n.contains(localeName))) {
      return;
    }

    if (localeNames.size() == 0) {
      loadLocales();
    }

    Properties p = new Properties();

    if (mergeWith != null) {
      if (!I18n.contains(mergeWith)) {
        load(mergeWith, null);
      }

      p.putAll((Properties) messagesMap.get(mergeWith));
    }

    FileInputStream fis = null;

    try {
      String filename = baseDir + localeNames.getProperty(localeName);

      // If the requested locale does not exist, use the default
      if (!new File(filename).exists()) {
        filename =
            baseDir
                + localeNames.getProperty(SystemGlobals.getValue(ConfigKeys.I18N_DEFAULT_ADMIN));
      }

      fis = new FileInputStream(filename);
      p.load(fis);
    } catch (IOException e) {
      throw new ForumException(e);
    } finally {
      if (fis != null) {
        try {
          fis.close();
        } catch (Exception e) {
        }
      }
    }

    messagesMap.put(localeName, p);

    watchForChanges(localeName);
  }
Ejemplo n.º 23
0
  public LostPasswordSpammer(final User user, final String mailTitle) {
    final String forumLink = ViewCommon.getForumLink();

    final String url =
        new StringBuilder()
            .append(forumLink)
            .append("user/recoverPassword/")
            .append(user.getActivationKey())
            .append(SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION))
            .toString();

    final SimpleHash params = new SimpleHash();
    params.put("url", url);
    params.put("user", user);

    final List<User> recipients = new ArrayList<User>();
    recipients.add(user);

    this.setUsers(recipients);
    this.setTemplateParams(params);

    super.prepareMessage(
        mailTitle, SystemGlobals.getValue(ConfigKeys.MAIL_LOST_PASSWORD_MESSAGE_FILE));
  }
Ejemplo n.º 24
0
  public static List getSmilies() {
    List list = (List) cache.get(FQN, ENTRIES);
    if (!contexted) {
      String forumLink = SystemGlobals.getValue(ConfigKeys.FORUM_LINK);

      for (Iterator iter = list.iterator(); iter.hasNext(); ) {
        Smilie s = (Smilie) iter.next();
        s.setUrl(s.getUrl().replaceAll("#CONTEXT#", forumLink).replaceAll("\\\\", ""));
      }

      cache.add(FQN, ENTRIES, list);
      contexted = true;
    }

    return list;
  }
Ejemplo n.º 25
0
  private static void loadLocales() {
    FileInputStream fis = null;

    try {
      fis = new FileInputStream(baseDir + SystemGlobals.getValue(ConfigKeys.LOCALES_NAMES));
      localeNames.load(fis);
    } catch (IOException e) {
      throw new ForumException(e);
    } finally {
      if (fis != null) {
        try {
          fis.close();
        } catch (Exception e) {
        }
      }
    }
  }
Ejemplo n.º 26
0
 private void init(String baseDir) throws IOException {
   SystemGlobals.initGlobals(baseDir, baseDir + "/phpbb2jforum/resource/SystemGlobals.properties");
   SystemGlobals.loadQueries(
       baseDir + "/phpbb2jforum/resource/" + SystemGlobals.getValue(ConfigKeys.DATABASE_QUERIES));
 }
Ejemplo n.º 27
0
 public static void changeBoardDefault(String newDefaultLanguage) {
   load(newDefaultLanguage, SystemGlobals.getValue(ConfigKeys.I18N_DEFAULT_ADMIN));
   defaultName = newDefaultLanguage;
 }
Ejemplo n.º 28
0
  /**
   * Setup common variables used by almost all templates.
   *
   * @param context SimpleHash The context to use
   * @param jforumContext JForumContext
   */
  public void prepareTemplateContext(SimpleHash context, ForumContext jforumContext) {

    LOG.trace("prepareTemplateContext");
    RequestContext request = JForumExecutionContext.getRequest();

    context.put("karmaEnabled", SecurityRepository.canAccess(SecurityConstants.PERM_KARMA_ENABLED));
    context.put("dateTimeFormat", SystemGlobals.getValue(ConfigKeys.DATE_TIME_FORMAT));
    context.put("autoLoginEnabled", SystemGlobals.getBoolValue(ConfigKeys.AUTO_LOGIN_ENABLED));
    context.put(
        "sso", ConfigKeys.TYPE_SSO.equals(SystemGlobals.getValue(ConfigKeys.AUTHENTICATION_TYPE)));
    context.put("contextPath", request.getContextPath());
    context.put("serverName", request.getServerName());
    context.put("templateName", SystemGlobals.getValue(ConfigKeys.TEMPLATE_DIR));
    context.put("extension", SystemGlobals.getValue(ConfigKeys.SERVLET_EXTENSION));
    context.put("serverPort", Integer.toString(request.getServerPort()));
    context.put("I18n", I18n.getInstance());
    context.put("version", SystemGlobals.getValue(ConfigKeys.VERSION));
    context.put("forumTitle", SystemGlobals.getValue(ConfigKeys.FORUM_PAGE_TITLE));
    context.put("pageTitle", SystemGlobals.getValue(ConfigKeys.FORUM_PAGE_TITLE));
    context.put("metaKeywords", SystemGlobals.getValue(ConfigKeys.FORUM_PAGE_METATAG_KEYWORDS));
    context.put(
        "metaDescription", SystemGlobals.getValue(ConfigKeys.FORUM_PAGE_METATAG_DESCRIPTION));
    context.put("forumLink", SystemGlobals.getValue(ConfigKeys.FORUM_LINK));
    context.put("homepageLink", SystemGlobals.getValue(ConfigKeys.HOMEPAGE_LINK));
    context.put("encoding", SystemGlobals.getValue(ConfigKeys.ENCODING));
    context.put(
        "bookmarksEnabled", SecurityRepository.canAccess(SecurityConstants.PERM_BOOKMARKS_ENABLED));
    context.put(
        "canAccessModerationLog",
        SecurityRepository.canAccess(SecurityConstants.PERM_MODERATION_LOG));
    context.put("JForumContext", jforumContext);
    context.put("timestamp", new Long(System.currentTimeMillis()));
    context.put("NoSpamURL", SystemGlobals.getValue("forum.nospam.url")); // Obfuscated
    // Javascript
    // URL
  }
Ejemplo n.º 29
0
 /**
  * Loads a new locale. If <code>localeName</code> is either null or empty, or if the locale is
  * already loaded, the method will return without executing any code.
  *
  * @param localeName The locale name to load
  */
 public static void load(String localeName) {
   load(localeName, SystemGlobals.getValue(ConfigKeys.I18N_DEFAULT));
 }
Ejemplo n.º 30
0
  public boolean dispatchMessages() {
    try {
      int sendDelay = SystemGlobals.getIntValue(ConfigKeys.MAIL_SMTP_DELAY);

      if (SystemGlobals.getBoolValue(ConfigKeys.MAIL_SMTP_AUTH)) {
        if (StringUtils.isNotEmpty(username) && StringUtils.isNotEmpty(password)) {
          boolean ssl = SystemGlobals.getBoolValue(ConfigKeys.MAIL_SMTP_SSL);

          Transport transport = this.session.getTransport(ssl ? "smtps" : "smtp");

          try {
            String host = SystemGlobals.getValue(ConfigKeys.MAIL_SMTP_HOST);

            transport.connect(host, username, password);

            if (transport.isConnected()) {
              for (Iterator<User> userIter = this.users.iterator(); userIter.hasNext(); ) {
                User user = userIter.next();

                if (this.needCustomization) {
                  this.defineUserMessage(user);
                }

                if (StringUtils.isNotEmpty(user.getEmail())) {
                  Address address = new InternetAddress(user.getEmail());
                  LOGGER.debug("Sending mail to: " + user.getEmail());
                  this.message.setRecipient(Message.RecipientType.TO, address);
                  Stats.record("Sent email", user.getEmail());
                  transport.sendMessage(this.message, new Address[] {address});
                }
                if (sendDelay > 0) {
                  try {
                    Thread.sleep(sendDelay);
                  } catch (InterruptedException ie) {
                    LOGGER.error("Error while Thread.sleep." + ie, ie);
                  }
                }
              }
            }
          } catch (Exception e) {
            throw new MailException(e);
          } finally {
            try {
              transport.close();
            } catch (Exception e) {
              LOGGER.error(e);
            }
          }
        }
      } else {
        for (Iterator<User> iter = this.users.iterator(); iter.hasNext(); ) {
          User user = iter.next();

          if (this.needCustomization) {
            this.defineUserMessage(user);
          }

          if (StringUtils.isNotEmpty(user.getEmail())) {
            Address address = new InternetAddress(user.getEmail());
            LOGGER.debug("Sending mail to: " + user.getEmail());
            this.message.setRecipient(Message.RecipientType.TO, address);
            Stats.record("Sent email", user.getEmail());
            Transport.send(this.message, new Address[] {address});
          }
          if (sendDelay > 0) {
            try {
              Thread.sleep(sendDelay);
            } catch (InterruptedException ie) {
              LOGGER.error("Error while Thread.sleep." + ie, ie);
            }
          }
        }
      }
    } catch (MessagingException e) {
      LOGGER.error("Error while dispatching the message. " + e, e);
    }

    return true;
  }