@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);
    }
  }
Example #2
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);
    }
  }
  @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(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;
  }
  @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("/"));
  }
  @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);
    }
  }
 @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("/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;
  }
Example #10
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(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"));
    }
  }
Example #12
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);
  }