@RequestMapping(value = "/remove-userpic.jsp", method = RequestMethod.POST)
  public ModelAndView removeUserpic(ServletRequest request, @RequestParam("id") User user)
      throws Exception {
    Template tmpl = Template.getTemplate(request);

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

    User currentUser = tmpl.getCurrentUser();

    if (!currentUser.isModerator() && currentUser.getId() != user.getId()) {
      throw new AccessViolationException("Not permitted");
    }

    if (user.isModerator()) {
      throw new AccessViolationException(
          "Пользователю " + user.getNick() + " нельзя удалить картинку");
    }

    if (user.getPhoto() == null) {
      throw new AccessViolationException("Пользователь " + user.getNick() + " картинки не имеет");
    }

    if (userDao.removePhoto(user, currentUser)) {
      logger.info("Clearing " + user.getNick() + " userpic by " + currentUser.getNick());
    } else {
      logger.debug("SKIP Clearing " + user.getNick() + " userpic by " + currentUser.getNick());
    }

    return redirectToProfile(user);
  }
  @RequestMapping(
      value = "/admin/search-reindex",
      method = RequestMethod.POST,
      params = "action=current")
  public ModelAndView reindexCurrentMonth(ServletRequest request) throws Exception {
    Template tmpl = Template.getTemplate(request);

    Connection db = LorDataSource.getConnection();

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

      tmpl.getCurrentUser().checkDelete();

      Calendar current = Calendar.getInstance();

      for (int i = 0; i < 3; i++) {
        searchQueueSender.updateMonth(current.get(Calendar.YEAR), current.get(Calendar.MONTH) + 1);
        current.add(Calendar.MONTH, -1);
      }

      return new ModelAndView("action-done", "message", "Scheduled reindex last 3 month");
    } finally {
      JdbcUtils.closeConnection(db);
    }
  }
Пример #3
0
  @RequestMapping(value = "/edit-vote.jsp", method = RequestMethod.GET)
  public ModelAndView showForm(HttpServletRequest request, @RequestParam("msgid") int msgid)
      throws Exception {
    Template tmpl = Template.getTemplate(request);

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

    Map<String, Object> params = new HashMap<String, Object>();
    params.put("msgid", msgid);

    Connection db = null;

    try {
      db = LorDataSource.getConnection();

      Poll poll = Poll.getPollByTopic(db, msgid);
      params.put("poll", poll);

      List<PollVariant> variants = poll.getPollVariants(db, Poll.ORDER_ID);
      params.put("variants", variants);

      return new ModelAndView("edit-vote", params);
    } finally {
      if (db != null) {
        db.close();
      }
    }
  }
Пример #4
0
  @RequestMapping(
      value = "/memories.jsp",
      params = {"remove"},
      method = RequestMethod.POST)
  public @ResponseBody void remove(ServletRequest request, @RequestParam("id") int id)
      throws Exception {
    Template tmpl = Template.getTemplate(request);

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

    User user = tmpl.getCurrentUser();
    user.checkBlocked();
    user.checkAnonymous();

    MemoriesListItem m = memoriesDao.getMemoriesListItem(id);

    if (m != null) {
      if (m.getUserid() != user.getId()) {
        throw new AccessViolationException("Нельзя удалить чужую запись");
      }

      memoriesDao.delete(id);
    }
  }
 /**
  * Возвращает объект User модератора, если текущая сессия не модераторская, тогда исключение
  *
  * @param request текущий http запрос
  * @return текущий модератор
  * @throws Exception если модератора нет
  */
 private static User getModerator(HttpServletRequest request) throws Exception {
   Template tmpl = Template.getTemplate(request);
   if (!tmpl.isModeratorSession()) {
     throw new AccessViolationException("Not moderator");
   }
   return tmpl.getCurrentUser();
 }
  @RequestMapping(method = RequestMethod.GET)
  public ModelAndView show(
      @ModelAttribute("form") EditRegisterRequest form,
      @PathVariable String nick,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {
    Template tmpl = Template.getTemplate(request);
    if (!tmpl.isSessionAuthorized()) {
      throw new AccessViolationException("Not authorized");
    }
    if (!tmpl.getNick().equals(nick)) {
      throw new AccessViolationException("Not authorized");
    }
    User user = tmpl.getCurrentUser();
    UserInfo userInfo = userDao.getUserInfoClass(user);

    ModelAndView mv = new ModelAndView("edit-reg");

    form.setEmail(user.getEmail());
    form.setUrl(userInfo.getUrl());
    form.setTown(userInfo.getTown());
    form.setName(user.getName());
    form.setInfo(StringEscapeUtils.unescapeHtml(userDao.getUserInfo(user)));

    response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");

    return mv;
  }
Пример #7
0
  @RequestMapping(method = RequestMethod.GET)
  public ModelAndView showForm(ServletRequest request) throws Exception {
    Template tmpl = Template.getTemplate(request);

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

    return new ModelAndView("edit-profile");
  }
  @RequestMapping(
      value = "/admin/search-reindex",
      method = RequestMethod.POST,
      params = "action=all")
  public ModelAndView reindexAll(ServletRequest request) throws Exception {
    Template tmpl = Template.getTemplate(request);

    Connection db = LorDataSource.getConnection();

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

      tmpl.getCurrentUser().checkDelete();

      Statement st = db.createStatement();

      ResultSet rs =
          st.executeQuery("SELECT min(postdate) FROM topics WHERE postdate!='epoch'::timestamp");

      if (!rs.next()) {
        throw new RuntimeException("no topics?!");
      }

      Timestamp startDate = rs.getTimestamp(1);

      rs.close();
      st.close();

      Calendar start = Calendar.getInstance();
      start.setTime(startDate);

      start.set(Calendar.DAY_OF_MONTH, 1);
      start.set(Calendar.HOUR, 0);
      start.set(Calendar.MINUTE, 0);

      for (Calendar i = Calendar.getInstance(); i.after(start); i.add(Calendar.MONTH, -1)) {
        searchQueueSender.updateMonth(i.get(Calendar.YEAR), i.get(Calendar.MONTH) + 1);
      }

      searchQueueSender.updateMonth(1970, 1);

      return new ModelAndView("action-done", "message", "Scheduled reindex");
    } finally {
      JdbcUtils.closeConnection(db);
    }
  }
Пример #9
0
 @ModelAttribute("filters")
 public static List<TrackerFilterEnum> getFilter(HttpServletRequest request) {
   Template tmpl = Template.getTemplate(request);
   if (tmpl.isSessionAuthorized()) {
     return Arrays.asList(TrackerFilterEnum.values());
   } else {
     List<TrackerFilterEnum> trackerFilters = new ArrayList<>();
     for (TrackerFilterEnum trackerFilter : TrackerFilterEnum.values()) {
       if ("mine".equals(trackerFilter.getValue())) {
         continue;
       }
       trackerFilters.add(trackerFilter);
     }
     return trackerFilters;
   }
 }
  @RequestMapping(value = "/groupmod.jsp", method = RequestMethod.GET)
  public ModelAndView showForm(@RequestParam("group") int id, ServletRequest request)
      throws Exception {
    Template tmpl = Template.getTemplate(request);

    if (!tmpl.isModeratorSession()) {
      throw new AccessViolationException("Not moderator");
    }

    Group group = groupDao.getGroup(id);

    ModelAndView mv = new ModelAndView("groupmod", "group", group);

    mv.getModel().put("groupInfo", prepareService.prepareGroupInfo(group, request.isSecure()));

    return mv;
  }
Пример #11
0
  @RequestMapping(
      value = "/memories.jsp",
      params = {"add"},
      method = RequestMethod.POST)
  public @ResponseBody Integer add(ServletRequest request, @RequestParam("msgid") int msgid)
      throws Exception {
    Template tmpl = Template.getTemplate(request);

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

    User user = tmpl.getCurrentUser();
    user.checkBlocked();
    user.checkAnonymous();

    Topic topic = messageDao.getById(msgid);
    if (topic.isDeleted()) {
      throw new UserErrorException("Тема удалена");
    }

    return memoriesDao.addToMemories(user.getId(), topic.getId());
  }
  @RequestMapping(value = "/groupmod.jsp", method = RequestMethod.POST)
  public ModelAndView modifyGroup(
      @RequestParam("group") int id,
      @RequestParam("title") String title,
      @RequestParam("info") String info,
      @RequestParam("urlName") String urlName,
      @RequestParam("longinfo") String longInfo,
      @RequestParam(value = "preview", required = false) String preview,
      @RequestParam(value = "resolvable", required = false) String resolvable,
      ServletRequest request)
      throws Exception {
    Template tmpl = Template.getTemplate(request);

    if (!tmpl.isModeratorSession()) {
      throw new AccessViolationException("Not moderator");
    }

    Group group = groupDao.getGroup(id);

    if (preview != null) {
      group.setTitle(title);
      group.setInfo(info);
      group.setLongInfo(longInfo);

      Map<String, Object> params = new HashMap<String, Object>();
      params.put("group", group);
      params.put("groupInfo", prepareService.prepareGroupInfo(group, request.isSecure()));
      params.put("preview", true);

      return new ModelAndView("groupmod", params);
    }

    groupDao.setParams(group, title, info, longInfo, resolvable != null, urlName);

    return new ModelAndView("action-done", "message", "Параметры изменены");
  }
Пример #13
0
  @RequestMapping(
      value = "/{section}/{group}/{id}/comments",
      produces = "application/json; charset=UTF-8",
      method = RequestMethod.GET)
  @ResponseBody
  public Map<String, Object> getComments(
      @PathVariable("section") String sectionName,
      @PathVariable("group") String groupName,
      @PathVariable("id") int msgid,
      @RequestParam(value = "page", defaultValue = "0") int page,
      HttpServletRequest request)
      throws Exception {
    Topic topic = topicDao.getById(msgid);
    Group group = groupDao.getGroup(topic.getGroupId());
    Section section = sectionService.getSection(group.getSectionId());

    if (!section.getUrlName().equals(sectionName)
        || !group.getUrlName().equals(groupName)
        || page < 0) {
      throw new MessageNotFoundException(msgid);
    }

    permissionService.checkView(topic, AuthUtil.getCurrentUser());

    CommentList comments = commentService.getCommentList(topic, false);

    CommentFilter cv = new CommentFilter(comments);

    int messagesPerPage = AuthUtil.getProfile().getMessages();

    List<Comment> commentsFiltered =
        cv.getCommentsForPage(false, page, messagesPerPage, ImmutableSet.<Integer>of());

    List<PreparedComment> preparedComments =
        prepareService.prepareCommentList(
            comments, commentsFiltered, request.isSecure(), Template.getTemplate(request), topic);

    return ImmutableMap.of(
        "comments",
        preparedComments,
        "topic",
        new ApiCommentTopicInfo(
            topic.getId(),
            topic.getLink(),
            permissionService.isCommentsAllowed(topic, AuthUtil.getCurrentUser())));
  }
Пример #14
0
  @RequestMapping("/people/{nick}/remarks")
  public ModelAndView showRemarks(
      ServletRequest request,
      @PathVariable String nick,
      @RequestParam(value = "offset", defaultValue = "0") int offset,
      @RequestParam(value = "sort", defaultValue = "0") int sortorder)
      throws Exception {
    Template tmpl = Template.getTemplate(request);
    if (!tmpl.isSessionAuthorized() || !tmpl.getCurrentUser().getNick().equals(nick)) {
      throw new AccessViolationException("Not authorized");
    }

    int count = userDao.getRemarkCount(tmpl.getCurrentUser());

    ModelAndView mv = new ModelAndView("view-remarks");

    int limit = tmpl.getProf().getMessages();

    if (count > 0) {
      if (offset >= count) {
        throw new UserErrorException("Offset is too long");
      }
      if (offset < 0) offset = 0;

      if (sortorder != 1) {
        sortorder = 0;
        mv.getModel().put("sortorder", "");
      } else {
        mv.getModel().put("sortorder", "&amp;sort=1");
      }

      List<Remark> remarks = userDao.getRemarkList(tmpl.getCurrentUser(), offset, sortorder, limit);
      List<PreparedRemark> preparedRemarks = prepareService.prepareRemarkList(remarks);

      mv.getModel().put("remarks", preparedRemarks);
    } else {
      mv.getModel().put("remarks", ImmutableList.of());
    }
    mv.getModel().put("offset", offset);
    mv.getModel().put("limit", limit);
    mv.getModel().put("hasMore", (count > (offset + limit)));

    return mv;
  }
Пример #15
0
  @RequestMapping("/tracker")
  public ModelAndView tracker(
      @RequestParam(value = "filter", defaultValue = "all") String filterAction,
      @RequestParam(value = "offset", required = false) Integer offset,
      HttpServletRequest request)
      throws Exception {

    if (offset == null) {
      offset = 0;
    } else {
      if (offset < 0 || offset > 300) {
        throw new UserErrorException("Некорректное значение offset");
      }
    }

    TrackerFilterEnum trackerFilter = getFilterValue(filterAction);

    Map<String, Object> params = new HashMap<>();
    params.put("mine", trackerFilter == TrackerFilterEnum.MINE);
    params.put("offset", offset);
    params.put("filter", trackerFilter.getValue());

    if (trackerFilter != TrackerFilterEnum.ALL) {
      params.put("addition_query", "&amp;filter=" + trackerFilter.getValue());
    } else {
      params.put("addition_query", "");
    }

    Calendar calendar = Calendar.getInstance();
    calendar.setTime(new Date());
    if (trackerFilter == TrackerFilterEnum.MINE) {
      calendar.add(Calendar.MONTH, -6);
    } else {
      calendar.add(Calendar.HOUR, -24);
    }
    Timestamp dateLimit = new Timestamp(calendar.getTimeInMillis());

    Template tmpl = Template.getTemplate(request);
    int messages = tmpl.getProf().getMessages();
    int topics = tmpl.getProf().getTopics();

    params.put("topics", topics);

    User user = tmpl.getCurrentUser();

    if (trackerFilter == TrackerFilterEnum.MINE) {
      if (!tmpl.isSessionAuthorized()) {
        throw new UserErrorException("Not authorized");
      }
      params.put("title", "Последние сообщения (мои темы)");
    } else {
      params.put("title", "Последние сообщения");
    }
    params.put(
        "msgs", trackerDao.getTrackAll(trackerFilter, user, dateLimit, topics, offset, messages));

    if (tmpl.isModeratorSession() && trackerFilter != TrackerFilterEnum.MINE) {
      params.put("newUsers", userDao.getNewUsers());
      params.put("deleteStats", deleteInfoDao.getRecentStats());
    }

    return new ModelAndView("tracker", params);
  }
Пример #16
0
  @RequestMapping(value = "/edit-vote.jsp", method = RequestMethod.POST)
  public ModelAndView editVote(
      HttpServletRequest request,
      @RequestParam("msgid") int msgid,
      @RequestParam("id") int id,
      @RequestParam("title") String title)
      throws Exception {
    Template tmpl = Template.getTemplate(request);

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

    Connection db = null;

    try {
      db = LorDataSource.getConnection();
      db.setAutoCommit(false);

      User user = User.getUser(db, tmpl.getNick());
      user.checkCommit();

      Poll poll = new Poll(db, id);

      PreparedStatement pstTitle = db.prepareStatement("UPDATE votenames SET title=? WHERE id=?");
      pstTitle.setInt(2, id);
      pstTitle.setString(1, HTMLFormatter.htmlSpecialChars(title));

      pstTitle.executeUpdate();

      PreparedStatement pstTopic = db.prepareStatement("UPDATE topics SET title=? WHERE id=?");
      pstTopic.setInt(2, msgid);
      pstTopic.setString(1, HTMLFormatter.htmlSpecialChars(title));

      pstTopic.executeUpdate();

      List<PollVariant> variants = poll.getPollVariants(db, Poll.ORDER_ID);
      for (PollVariant var : variants) {
        String label = new ServletParameterParser(request).getString("var" + var.getId());

        if (label == null || label.trim().length() == 0) {
          var.remove(db);
        } else {
          var.updateLabel(db, label);
        }
      }

      for (int i = 1; i <= 3; i++) {
        String label = new ServletParameterParser(request).getString("new" + i);

        if (label != null && label.trim().length() > 0) {
          poll.addNewVariant(db, label);
        }
      }

      logger.info("Отредактирован опрос" + id + " пользователем " + user.getNick());

      db.commit();

      Random random = new Random();

      return new ModelAndView(
          new RedirectView("view-message.jsp?msgid=" + msgid + "&nocache=" + random.nextInt()));
    } finally {
      if (db != null) {
        db.close();
      }
    }
  }
  @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"));
    }
  }
Пример #18
0
  @RequestMapping(method = RequestMethod.POST)
  public ModelAndView editProfile(ServletRequest request) throws Exception {
    Template tmpl = Template.getTemplate(request);

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

    String profile = tmpl.getNick();

    int topics = Integer.parseInt(request.getParameter("topics"));
    int messages = Integer.parseInt(request.getParameter("messages"));
    int tags = Integer.parseInt(request.getParameter("tags"));

    if (topics <= 0 || topics > 500) {
      throw new BadInputException("некорректное число тем");
    }

    if (messages <= 0 || messages > 1000) {
      throw new BadInputException("некорректное число сообщений");
    }

    if (tags <= 0 || tags > 100) {
      throw new BadInputException("некорректное число меток в облаке");
    }

    if (!DefaultProfile.getStyleList().contains(request.getParameter("style"))) {
      throw new BadInputException("неправльное название темы");
    }

    tmpl.getProf().setTopics(topics);
    tmpl.getProf().setMessages(messages);
    tmpl.getProf().setTags(tags);
    tmpl.getProf().setShowNewFirst("on".equals(request.getParameter("newfirst")));
    tmpl.getProf().setShowPhotos("on".equals(request.getParameter("photos")));
    tmpl.getProf().setHideAdsense("on".equals(request.getParameter("hideAdsense")));
    tmpl.getProf().setShowGalleryOnMain("on".equals(request.getParameter("mainGallery")));
    tmpl.getProf().setFormatMode(request.getParameter("format_mode"));
    tmpl.getProf().setStyle(request.getParameter("style")); // TODO убрать как только
    userDao.setStyle(tmpl.getCurrentUser(), request.getParameter("style"));

    tmpl.getProf().setShowSocial("on".equals(request.getParameter("showSocial")));

    String avatar = request.getParameter("avatar");

    if (!DefaultProfile.getAvatars().contains(avatar)) {
      throw new BadInputException("invalid avatar value");
    }

    tmpl.getProf().setAvatarMode(avatar);

    tmpl.getProf().setThreeColumnsOnMain("on".equals(request.getParameter("3column")));

    tmpl.getProf().setShowAnonymous("on".equals(request.getParameter("showanonymous")));
    tmpl.getProf().setUseHover("on".equals(request.getParameter("hover")));

    tmpl.writeProfile(profile);

    return new ModelAndView(new RedirectView("/"));
  }