@Override
  protected void createFeed(SyndFeed feed, Map model) {
    @SuppressWarnings("unchecked")
    List<PreparedUserEvent> list = (List<PreparedUserEvent>) model.get("topicsList");
    String s = "Ответы на комментарии пользователя " + model.get("nick");
    feed.setTitle(s);
    feed.setLink("http://www.linux.org.ru");
    feed.setUri("http://www.linux.org.ru");
    feed.setAuthor("");
    feed.setDescription(s);

    Date lastModified;
    if (!list.isEmpty()) {
      lastModified = list.get(0).getEvent().getEventDate();
    } else {
      lastModified = new Date();
    }
    feed.setPublishedDate(lastModified);

    List<SyndEntry> entries = new ArrayList<>();
    feed.setEntries(entries);
    for (PreparedUserEvent preparedUserEvent : list) {
      UserEvent item = preparedUserEvent.getEvent();

      SyndEntry feedEntry = new SyndEntryImpl();
      feedEntry.setPublishedDate(item.getEventDate());
      feedEntry.setTitle(StringEscapeUtils.unescapeHtml4(item.getSubj()));

      String link;

      if (item.getCid() != 0) {
        feedEntry.setAuthor(preparedUserEvent.getAuthor().getNick());

        link =
            String.format(
                "http://www.linux.org.ru/jump-message.jsp?msgid=%s&cid=%s",
                String.valueOf(item.getTopicId()), String.valueOf(item.getCid()));
      } else {
        link =
            String.format(
                "http://www.linux.org.ru/view-message.jsp?msgid=%s",
                String.valueOf(item.getTopicId()));
      }

      feedEntry.setLink(link);
      feedEntry.setUri(link);

      if (preparedUserEvent.getMessageText() != null) {
        SyndContent message = new SyndContentImpl();
        message.setValue(StringUtil.removeInvalidXmlChars(preparedUserEvent.getMessageText()));
        message.setType("text/html");
        feedEntry.setDescription(message);
      }
      entries.add(feedEntry);
    }
  }
Example #2
0
  public SearchItem(
      SolrDocument doc,
      UserDao userDao,
      MsgbaseDao msgbaseDao,
      LorCodeService lorCodeService,
      boolean secure) {
    msgid = (String) doc.getFieldValue("id");
    title = (String) doc.getFieldValue("title");
    topicTitle = (String) doc.getFieldValue("topic_title");
    int userid = (Integer) doc.getFieldValue("user_id");
    Date postdate_dt = (Date) doc.getFieldValue("postdate");
    postdate = new Timestamp(postdate_dt.getTime());
    topic = (Integer) doc.getFieldValue("topic_id");
    section = (String) doc.getFieldValue("section");

    if (!"wiki".equals(section)) {
      virtualWiki = null;
      MessageText messageText = msgbaseDao.getMessageText(Integer.valueOf(msgid));
      String rawMessage = messageText.getText();
      if (messageText.isLorcode()) {
        message = lorCodeService.parseComment(rawMessage, secure);
      } else {
        message = rawMessage;
      }
    } else {
      // Wiki id like <virtual_wiki>-<topic_id>
      String[] msgIds = msgid.split("-");
      if (msgIds.length != 2) {
        throw new RuntimeException("Invalid wiki ID");
      }

      String content = msgbaseDao.getMessageTextFromWiki(Integer.valueOf(msgIds[1]));
      String msg = StringUtil.escapeHtml(content.substring(0, Math.min(1300, content.length())));
      if (Math.min(1300, content.length()) == 1300) {
        message = msg + "...";
      } else {
        message = msg;
      }
      virtualWiki = msgIds[0];
    }
    try {
      user = userDao.getUserCached(userid);
    } catch (UserNotFoundException e) {
      throw new RuntimeException(e);
    }
  }
  @Override
  public void validate(Object o, Errors errors) {
    RegisterRequest form = (RegisterRequest) o;

    /*
    Nick validate
     */

    String nick = form.getNick();

    if (Strings.isNullOrEmpty(nick)) {
      errors.rejectValue("nick", null, "не задан nick");
    }

    if (nick != null && !StringUtil.checkLoginName(nick)) {
      errors.rejectValue("nick", null, "некорректное имя пользователя");
    }

    if (nick != null && nick.length() > User.MAX_NICK_LENGTH) {
      errors.rejectValue("nick", null, "слишком длинное имя пользователя");
    }

    /*
    Password validate
     */

    String password = Strings.emptyToNull(form.getPassword());
    String password2 = Strings.emptyToNull(form.getPassword2());

    if (Strings.isNullOrEmpty(password)) {
      errors.reject("password", null, "пароль не может быть пустым");
    }
    if (Strings.isNullOrEmpty(password2)) {
      errors.reject("password2", null, "пароль не может быть пустым");
    }

    if (password != null && password.equalsIgnoreCase(nick)) {
      errors.reject(password, null, "пароль не может совпадать с логином");
    }

    if (form.getPassword2() != null
        && form.getPassword() != null
        && !form.getPassword().equals(form.getPassword2())) {
      errors.reject(null, "введенные пароли не совпадают");
    }

    if (!Strings.isNullOrEmpty(form.getPassword())
        && form.getPassword().length() < MIN_PASSWORD_LEN) {
      errors.reject(
          "password", null, "слишком короткий пароль, минимальная длина: " + MIN_PASSWORD_LEN);
    }

    /*
    Email validate
     */

    if (Strings.isNullOrEmpty(form.getEmail())) {
      errors.rejectValue("email", null, "Не указан e-mail");
    } else {
      try {
        InternetAddress mail = new InternetAddress(form.getEmail());
        checkEmail(mail, errors);
      } catch (AddressException e) {
        errors.rejectValue("email", null, "Некорректный e-mail: " + e.getMessage());
      }
    }

    /*
    Rules validate
     */

    if (Strings.isNullOrEmpty(form.getRules()) || !"okay".equals(form.getRules())) {
      errors.reject("rules", null, "Вы не согласились с правилами");
    }
  }
  public List<TrackerItem> getTrackAll(
      TrackerFilterEnum filter,
      User currentUser,
      Date startDate,
      int topics,
      int offset,
      final int messagesInPage) {

    MapSqlParameterSource parameter = new MapSqlParameterSource();
    parameter.addValue("interval", startDate);
    parameter.addValue("topics", topics);
    parameter.addValue("offset", offset);

    String partIgnored;

    if (currentUser != null) {
      partIgnored = queryPartIgnored + queryPartTagIgnored;
      parameter.addValue("userid", currentUser.getId());
    } else {
      partIgnored = "";
    }

    String partFilter;
    switch (filter) {
      case ALL:
        partFilter = "";
        break;
      case NOTALKS:
        partFilter = queryPartNoTalks;
        break;
      case MAIN:
        partFilter = queryPartMain;
        break;
      case TECH:
        partFilter = queryPartTech;
        break;
      default:
        partFilter = "";
    }

    boolean showUncommited =
        currentUser != null && (currentUser.isModerator() || currentUser.isCorrector());

    String partUncommited = showUncommited ? "" : noUncommited;

    String query;

    query =
        String.format(
            queryTrackerMain,
            partUncommited,
            partIgnored,
            partFilter,
            partUncommited,
            partIgnored,
            partFilter);

    SqlRowSet resultSet = jdbcTemplate.queryForRowSet(query, parameter);

    List<TrackerItem> res = new ArrayList<>(topics);

    while (resultSet.next()) {
      User author = userDao.getUserCached(resultSet.getInt("author"));
      int msgid = resultSet.getInt("id");
      Timestamp lastmod = resultSet.getTimestamp("lastmod");
      int stat1 = resultSet.getInt("stat1");
      int groupId = resultSet.getInt("gid");
      String groupTitle = resultSet.getString("gtitle");
      String title = StringUtil.makeTitle(resultSet.getString("title"));
      int cid = resultSet.getInt("cid");
      User lastCommentBy;
      try {
        int id = resultSet.getInt("last_comment_by");

        if (id != 0) {
          lastCommentBy = userDao.getUserCached(id);
        } else {
          lastCommentBy = null;
        }
      } catch (UserNotFoundException e) {
        throw new RuntimeException(e);
      }
      boolean resolved = resultSet.getBoolean("resolved");
      int section = resultSet.getInt("section");
      String groupUrlName = resultSet.getString("urlname");
      Timestamp postdate = resultSet.getTimestamp("postdate");
      boolean uncommited = resultSet.getBoolean("smod") && !resultSet.getBoolean("moderate");
      int pages = Topic.getPageCount(stat1, messagesInPage);

      ImmutableList<String> tags;

      tags = topicTagService.getTagsForTitle(msgid);

      res.add(
          new TrackerItem(
              author,
              msgid,
              lastmod,
              stat1,
              groupId,
              groupTitle,
              title,
              cid,
              lastCommentBy,
              resolved,
              section,
              groupUrlName,
              postdate,
              uncommited,
              pages,
              tags));
    }

    return res;
  }
  @RequestMapping(method = RequestMethod.POST)
  public ModelAndView edit(
      HttpServletRequest request,
      @Valid @ModelAttribute("form") EditRegisterRequest form,
      Errors errors)
      throws Exception {
    Template tmpl = Template.getTemplate(request);

    if (!tmpl.isSessionAuthorized()) {
      throw new AccessViolationException("Not authorized");
    }

    String nick = tmpl.getNick();
    String password = Strings.emptyToNull(form.getPassword());

    if (password != null && password.equalsIgnoreCase(nick)) {
      errors.reject(null, "пароль не может совпадать с логином");
    }

    InternetAddress mail = null;

    if (!Strings.isNullOrEmpty(form.getEmail())) {
      try {
        mail = new InternetAddress(form.getEmail());
      } catch (AddressException e) {
        errors.rejectValue("email", null, "Некорректный e-mail: " + e.getMessage());
      }
    }

    String url = null;

    if (!Strings.isNullOrEmpty(form.getUrl())) {
      url = URLUtil.fixURL(form.getUrl());
    }

    String name = Strings.emptyToNull(form.getName());

    if (name != null) {
      name = StringUtil.escapeHtml(name);
    }

    String town = null;

    if (!Strings.isNullOrEmpty(form.getTown())) {
      town = StringUtil.escapeHtml(form.getTown());
    }

    String info = null;

    if (!Strings.isNullOrEmpty(form.getInfo())) {
      info = StringUtil.escapeHtml(form.getInfo());
    }

    ipBlockDao.checkBlockIP(request.getRemoteAddr(), errors, tmpl.getCurrentUser());

    boolean emailChanged = false;

    User user = userDao.getUser(nick);

    if (Strings.isNullOrEmpty(form.getOldpass())) {
      errors.rejectValue("oldpass", null, "Для изменения регистрации нужен ваш пароль");
    } else if (!user.matchPassword(form.getOldpass())) {
      errors.rejectValue("oldpass", null, "Неверный пароль");
    }

    user.checkAnonymous();

    String newEmail = null;

    if (mail != null) {
      if (user.getEmail() != null && user.getEmail().equals(form.getEmail())) {
        newEmail = null;
      } else {
        if (userDao.getByEmail(mail.getAddress(), false) != null) {
          errors.rejectValue("email", null, "такой email уже используется");
        }

        newEmail = mail.getAddress();

        emailChanged = true;
      }
    }

    if (!errors.hasErrors()) {
      userDao.updateUser(user, name, url, newEmail, town, password, info);

      if (emailChanged) {
        emailService.sendEmail(user.getNick(), mail.getAddress(), false);
      }
    } else {
      return new ModelAndView("edit-reg");
    }

    if (emailChanged) {
      String msg =
          "Обновление регистрации прошло успешно. Ожидайте письма с кодом активации смены email.";

      return new ModelAndView("action-done", "message", msg);
    } else {
      return new ModelAndView(new RedirectView("/people/" + nick + "/profile"));
    }
  }