private List<PublicationDetail> getLastUpdatedPublicationsSince(
     String spaceId, int sinceNbDays, int nbPublis) {
   try {
     return getPublicationHelper().getUpdatedPublications(spaceId, sinceNbDays, nbPublis);
   } catch (ClassNotFoundException e) {
     SilverTrace.error("lookAurora", "LookAuroraHelper.getLastUpdatedPublicationsSince", "", e);
   } catch (InstantiationException e) {
     SilverTrace.error("lookAurora", "LookAuroraHelper.getLastUpdatedPublicationsSince", "", e);
   } catch (IllegalAccessException e) {
     SilverTrace.error("lookAurora", "LookAuroraHelper.getLastUpdatedPublicationsSince", "", e);
   }
   return new ArrayList<PublicationDetail>();
 }
 private List<NextEventsDate> getNextEvents(boolean fetchOnlyImportant, String... almanachIds) {
   List<NextEventsDate> result = new ArrayList<NextEventsDate>();
   try {
     List<EventOccurrence> events = getAlmanachBm().getNextEventOccurrences(almanachIds);
     Date today = new Date();
     Date date = null;
     NextEventsDate nextEventsDate = null;
     for (EventOccurrence event : events) {
       if (Administration.get()
           .isComponentAvailable(event.getEventDetail().getInstanceId(), getUserId())) {
         if (!fetchOnlyImportant || (fetchOnlyImportant && event.isPriority())) {
           Date eventDate = event.getStartDate().asDate();
           if (DateUtil.compareTo(today, eventDate, true) != 0) {
             if (date == null || DateUtil.compareTo(date, eventDate, true) != 0) {
               nextEventsDate = new NextEventsDate(eventDate);
               result.add(nextEventsDate);
               date = eventDate;
             }
             nextEventsDate.addEvent(event);
           }
         }
       }
     }
   } catch (Exception e) {
     SilverTrace.error("lookAurora", "LookAuroraHelper.getNextEvents", "", e);
   }
   return result;
 }
 private List<News> getNewsByComponentId(String appId) {
   try {
     if (!Administration.get().isComponentAvailable(appId, getUserId())) {
       return new ArrayList<News>();
     }
   } catch (Exception e) {
     SilverTrace.error("lookAurora", "LookAuroraHelper.getNewsByComponentId", "", e);
   }
   QuickInfoService service = QuickInfoService.get();
   return service.getVisibleNews(appId);
 }
  @Override
  public String getDestination(String objectId, HttpServletRequest req, HttpServletResponse res)
      throws Exception {
    MainSessionController mainSessionCtrl = util.getMainSessionController(req);
    String language = I18NHelper.defaultLanguage;
    if (mainSessionCtrl != null) {
      language = mainSessionCtrl.getFavoriteLanguage();
    }
    SimpleDocumentPK pk = new SimpleDocumentPK(objectId);
    if (StringUtil.isLong(objectId)) {
      pk.setOldSilverpeasId(Long.parseLong(objectId));
    }

    SimpleDocument attachment =
        AttachmentServiceProvider.getAttachmentService().searchDocumentById(pk, language);
    if (attachment == null) {
      return null;
    }
    String componentId = attachment.getInstanceId();
    String foreignId = attachment.getForeignId();

    if (isUserLogin(req) && isUserAllowed(req, componentId)) {
      boolean isAccessAuthorized = true;
      if (componentId.startsWith("kmelia")) {
        try {
          ComponentAuthorization security =
              (ComponentAuthorization) Class.forName(KMELIA_SECURITY_CLASS).newInstance();
          isAccessAuthorized = security.isAccessAuthorized(componentId, getUserId(req), foreignId);
        } catch (Exception e) {
          SilverTrace.error(
              "util",
              "GoToFile.doPost",
              "root.EX_CLASS_NOT_INITIALIZED",
              "org.silverpeas.components.kmelia.KmeliaAuthorization",
              e);
          return null;
        }
      }
      if (isAccessAuthorized) {
        res.setCharacterEncoding(CharEncoding.UTF_8);
        res.setContentType("text/html; charset=utf-8");
        String fileName = ClientBrowserUtil.rfc2047EncodeFilename(req, attachment.getFilename());
        res.setHeader("Content-Disposition", "inline; filename=\"" + fileName + "\"");
        return URLUtil.getFullApplicationURL(req) + encodeFilename(attachment.getAttachmentURL());
      }
    }
    return "ComponentId="
        + componentId
        + "&AttachmentId="
        + objectId
        + "&Mapping=File&ForeignId="
        + foreignId;
  }
  protected static void createCropThumbnailFileOnServer(
      String pathOriginalFile,
      String pathCropdir,
      String pathCropFile,
      ThumbnailDetail thumbnail,
      int thumbnailWidth,
      int thumbnailHeight) {
    try {
      // Creates folder if not exists
      File dir = new File(pathCropdir);
      if (!dir.exists()) {
        FileFolderManager.createFolder(pathCropdir);
      }
      // create empty file
      File cropFile = new File(pathCropFile);
      if (!cropFile.exists()) {
        cropFile.createNewFile();
      }

      File originalFile = new File(pathOriginalFile);
      BufferedImage bufferOriginal = ImageIO.read(originalFile);
      // crop image
      BufferedImage cropPicture =
          bufferOriginal.getSubimage(
              thumbnail.getXStart(),
              thumbnail.getYStart(),
              thumbnail.getXLength(),
              thumbnail.getYLength());
      BufferedImage cropPictureFinal =
          new BufferedImage(thumbnailWidth, thumbnailHeight, BufferedImage.TYPE_INT_RGB);
      // Redimensionnement de l'image
      Graphics2D g2 = cropPictureFinal.createGraphics();
      g2.setRenderingHint(
          RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BICUBIC);
      g2.drawImage(cropPicture, 0, 0, thumbnailWidth, thumbnailHeight, null);
      g2.dispose();

      // save crop image
      String extension = FilenameUtils.getExtension(originalFile.getName());
      ImageIO.write(cropPictureFinal, extension, cropFile);
    } catch (Exception e) {
      SilverTrace.warn(
          "thumbnail",
          "ThumbnailController.createThumbnailFileOnServer()",
          "thumbnail_MSG_CREATE_CROP_FILE_KO",
          "originalFileName="
              + thumbnail.getOriginalFileName()
              + " cropFileName = "
              + thumbnail.getCropFileName(),
          e);
    }
  }
Example #6
0
  public synchronized Connection getConnection() {
    if (!isOk() && isLocalConnection) {

      try {
        createConnection();
      } catch (UtilException e) {
        SilverTrace.error("util", "Schema.getConnection", "util.CAN_T_CLOSE_CONNECTION", e);
      }
    } else {

    }

    return connection;
  }
 private static void deleteThumbnailFileOnServer(String componentId, String fileName) {
   String path = getImageDirectory(componentId) + fileName;
   try {
     SilverpeasFile image = SilverpeasFileProvider.getFile(path);
     image.delete();
   } catch (Exception e) {
     SilverTrace.warn(
         "thumbnail",
         "ThumbnailController.deleteThumbnailFileOnServer(String componentId, String fileName)",
         "thumbnail_MSG_NOT_DELETE_FILE",
         "filePath=" + path,
         e);
   }
 }
 private ContentManager getContentManager() {
   if (contentManager == null) {
     try {
       contentManager = new ContentManager();
     } catch (Exception e) {
       SilverTrace.fatal(
           "quickinfo",
           "QuickInfoContentManager.getContentManager()",
           "root.EX_UNKNOWN_CONTENT_MANAGER",
           e);
     }
   }
   return contentManager;
 }
 public Questions getQuestions() {
   Questions faqs = new Questions();
   QuestionManager qm = QuestionManagerProvider.getQuestionManager();
   String appId = getSettings("home.faq.appId", "");
   int nb = getSettings("home.faq.nb", 1);
   if (StringUtil.isDefined(appId)) {
     faqs.setAppId(appId);
     try {
       String[] profiles = getOrganisationController().getUserProfiles(getUserId(), appId);
       SilverpeasRole role = SilverpeasRole.getGreaterFrom(SilverpeasRole.from(profiles));
       faqs.setCanAskAQuestion(role.isGreaterThanOrEquals(SilverpeasRole.writer));
       List<Question> questions = (List<Question>) qm.getQuestions(appId);
       if (questions != null && !questions.isEmpty()) {
         if (nb > questions.size()) nb = questions.size();
         if ("random".equalsIgnoreCase(getSettings("home.faq.display", "random"))
             && questions.size() > 1
             && questions.size() > nb) {
           Random random = new Random();
           int j = 0;
           while (j < nb) {
             int i = random.nextInt(questions.size() - 1);
             Question question = questions.get(i);
             boolean tryagain = false;
             for (Question q : faqs.getList()) {
               if (question.getPK().getId().equals(q.getPK().getId())) {
                 tryagain = true;
                 break;
               }
             }
             if (!tryagain) {
               faqs.add(question);
               j++;
             }
           }
         } else {
           for (int i = 0; i < nb; i++) {
             faqs.add(questions.get(i));
           }
         }
         return faqs;
       }
     } catch (QuestionReplyException e) {
       SilverTrace.error(
           "lookAurora", "LookAuroraHelper.LookAuroraHelper", "root.MSG_GEN_PARAM_VALUE", e);
     }
   }
   return null;
 }
  private List<News> getDelegatedNews() {
    List<News> news = new ArrayList<News>();
    List<DelegatedNews> delegatedNews = delegatedNewsService.getAllValidDelegatedNews();
    try {
      for (DelegatedNews delegated : delegatedNews) {
        if (Administration.get().isComponentAvailable(delegated.getInstanceId(), getUserId())) {
          News aNews = new News(delegated.getPublicationDetail());
          aNews.setPublicationId(delegated.getPublicationDetail().getId());
          news.add(aNews);
        }
      }
    } catch (Exception e) {
      SilverTrace.error("lookAurora", "LookAuroraHelper.getDelegatedNews", "", e);
    }

    return news;
  }
 @Override
 public void moveStat(ForeignPK toForeignPK, int actionType, String objectType) {
   SilverTrace.info(
       "statistic", "DefaultStatisticService.deleteHistoryByAction", "root.MSG_GEN_ENTER_METHOD");
   Connection con = getConnection();
   try {
     HistoryObjectDAO.move(con, toForeignPK, actionType, objectType);
   } catch (Exception e) {
     throw new StatisticRuntimeException(
         "DefaultStatisticService().addObjectToHistory()",
         SilverpeasRuntimeException.ERROR,
         "statistic.CANNOT_ADD_VISITE_NODE",
         e);
   } finally {
     DBUtil.close(con);
   }
 }
  @Override
  public String doAction(HttpServletRequest request) {
    HttpSession session = request.getSession(true);
    MainSessionController controller =
        (MainSessionController)
            session.getAttribute(MainSessionController.MAIN_SESSION_CONTROLLER_ATT);
    if (controller == null) {
      return "/Login.jsp";
    }

    SettingBundle settings =
        ResourceLocator.getSettingBundle(
            "org.silverpeas.authentication.settings.passwordExpiration");
    String passwordChangeURL =
        settings.getString("passwordChangeURL", "/defaultPasswordAboutToExpire.jsp");

    UserDetail ud = controller.getCurrentUserDetail();
    try {
      String login = ud.getLogin();
      String domainId = ud.getDomainId();
      String oldPassword = request.getParameter("oldPassword");
      String newPassword = request.getParameter("newPassword");
      AuthenticationCredential credential =
          AuthenticationCredential.newWithAsLogin(login)
              .withAsPassword(oldPassword)
              .withAsDomainId(domainId);
      AuthenticationService authenticator = AuthenticationServiceProvider.getService();
      authenticator.changePassword(credential, newPassword);

      GraphicElementFactory gef =
          (GraphicElementFactory)
              session.getAttribute(GraphicElementFactory.GE_FACTORY_SESSION_ATT);
      String favoriteFrame = gef.getLookFrame();

      return "/Main/" + favoriteFrame;
    } catch (AuthenticationException e) {
      SilverTrace.error(
          "peasCore",
          "effectiveChangePasswordHandler.doAction()",
          "peasCore.EX_USER_KEY_NOT_FOUND",
          e);
      return performUrlChangePasswordError(request, passwordChangeURL, ud);
    }
  }
  public List<City> getWeatherCities() {
    if (getSettings("home.weather", false) == false) {
      return null;
    }

    List<City> cities = new ArrayList<City>();

    String[] woeids = StringUtil.split(getSettings("home.weather.woeid", ""), ",");
    String[] labels = StringUtil.split(getSettings("home.weather.cities", ""), ",");

    for (int i = 0; i < woeids.length; i++) {
      try {
        cities.add(new City(woeids[i], labels[i]));
      } catch (Exception e) {
        SilverTrace.error("lookSDIS84", "LookAuroraHelper.getWeatherCities", "ERROR", e);
      }
    }
    return cities;
  }
  public List<EventOccurrence> getTodayEvents() {
    List<EventOccurrence> availableEvents = new ArrayList<EventOccurrence>();
    try {
      List<EventOccurrence> events =
          getAlmanachBm()
              .getEventOccurrencesInPeriod(
                  Period.from(new Date(), PeriodType.day, "fr"), getAlmanachIds());
      for (EventOccurrence event : events) {
        if (Administration.get()
            .isComponentAvailable(event.getEventDetail().getInstanceId(), getUserId())) {
          availableEvents.add(event);
        }
      }
    } catch (Exception e) {
      SilverTrace.error("lookAurora", "LookAuroraHelper.getTodayEvents", "", e);
    }

    return availableEvents;
  }
 @Override
 public void send(final NotifMediaType mediaType) {
   if (notification != null) {
     try {
       final NotificationSender sender = new NotificationSender(notification.getComponentId());
       if (mediaType != null) {
         sender.notifyUser(mediaType.getId(), notification);
       } else {
         sender.notifyUser(notification);
       }
     } catch (final NotificationManagerException e) {
       SilverTrace.warn(
           "notification",
           "IUserNotification.send()",
           "notification.EX_IMPOSSIBLE_DALERTER_LES_UTILISATEURS",
           "componentId=" + notification.getComponentId(),
           e);
     }
   }
 }
 @Override
 public Collection<HistoryObjectDetail> getHistoryByObjectAndUser(
     ForeignPK foreignPK, int action, String objectType, String userId) {
   SilverTrace.info(
       "statistic",
       "DefaultStatisticService.getHistoryByObjectAndUser",
       "root.MSG_GEN_ENTER_METHOD");
   Connection con = getConnection();
   try {
     return HistoryObjectDAO.getHistoryDetailByObjectAndUser(con, foreignPK, objectType, userId);
   } catch (Exception e) {
     throw new StatisticRuntimeException(
         "DefaultStatisticService().getHistoryByObjectAndUser()",
         SilverpeasRuntimeException.ERROR,
         "statistic.CANNOT_GET_HISTORY_STATISTICS_PUBLICATION",
         e);
   } finally {
     DBUtil.close(con);
   }
 }
  protected static void cropFromPath(
      String pathOriginalFile,
      ThumbnailDetail thumbDetailComplete,
      int thumbnailHeight,
      int thumbnailWidth)
      throws IOException, ThumbnailException {
    File originalFile = new File(pathOriginalFile);
    BufferedImage bufferOriginal = ImageIO.read(originalFile);
    if (bufferOriginal == null) {
      SilverTrace.error(
          "thumbnail",
          "ThumbnailController.cropFromPath(int thumbnailWidth, "
              + "int thumbnailHeight,ThumbnailDetail thumbDetailComplete)",
          "thumbnail.EX_MSG_NOT_AN_IMAGE",
          "pathOriginalFile=" + pathOriginalFile);
      throw new ThumbnailException(
          "ThumbnailBmImpl.cropFromPath()",
          SilverpeasException.ERROR,
          "thumbnail.EX_MSG_NOT_AN_IMAGE");
    } else {
      thumbDetailComplete.setXStart(0);
      thumbDetailComplete.setYStart(0);
      thumbDetailComplete.setXLength(bufferOriginal.getWidth());
      thumbDetailComplete.setYLength(bufferOriginal.getHeight());

      String pathCropFile =
          getImageDirectory(thumbDetailComplete.getInstanceId())
              + thumbDetailComplete.getCropFileName();
      createCropThumbnailFileOnServer(
          pathOriginalFile,
          getImageDirectory(thumbDetailComplete.getInstanceId()),
          pathCropFile,
          thumbDetailComplete,
          thumbnailWidth,
          thumbnailHeight);
      getThumbnailService().updateThumbnail(thumbDetailComplete);
    }
  }
  private Collection<HistoryByUser> getHistoryByObject(
      ForeignPK foreignPK, int action, String objectType, UserDetail[] users) {
    SilverTrace.info(
        "statistic", "DefaultStatisticService.getHistoryByObject()", "root.MSG_GEN_ENTER_METHOD");
    Collection<HistoryObjectDetail> list;
    try {
      list = getHistoryByAction(foreignPK, action, objectType);
    } catch (Exception e) {
      throw new StatisticRuntimeException(
          "DefaultStatisticService.getHistoryByObject()",
          SilverpeasRuntimeException.ERROR,
          "statistic.EX_IMPOSSIBLE_DOBTENIR_LETAT_DES_LECTURES",
          e);
    }
    String[] readerIds = new String[list.size()];
    Date[] date = new Date[list.size()];
    Iterator<HistoryObjectDetail> it = list.iterator();
    int i = 0;
    while (it.hasNext()) {
      HistoryObjectDetail historyObject = it.next();
      readerIds[i] = historyObject.getUserId();
      date[i] = historyObject.getDate();
      i++;
    }
    UserDetail[] controlledUsers =
        OrganizationControllerProvider.getOrganisationController().getUserDetails(readerIds);

    // ajouter à la liste "allUsers" (liste des users des rôles) les users ayant lu mais ne faisant
    // pas partis d'un rôle
    int compteur = 0;
    Collection<UserDetail> allUsers = new ArrayList<>(users.length + controlledUsers.length);
    for (int j = 0; j < users.length; j++) {
      allUsers.add(users[j]);
      compteur = j + 1;
    }
    for (int j = compteur; j < controlledUsers.length; j++) {
      if (!allUsers.contains(controlledUsers[j])) {
        allUsers.add(controlledUsers[j]);
      }
    }

    // création de la liste de tous les utilisateur ayant le droit de lecture
    Collection<HistoryByUser> statByUser = new ArrayList<>(allUsers.size());
    for (UserDetail user : allUsers) {
      if (user != null) {
        HistoryByUser historyByUser = new HistoryByUser(user, null, 0);
        statByUser.add(historyByUser);
      }
    }

    // création d'une liste des accès par utilisateur
    Map<UserDetail, Date> byUser = new HashMap<>(controlledUsers.length);
    Map<UserDetail, Integer> nbAccessbyUser = new HashMap<>(controlledUsers.length);
    for (int j = 0; j < controlledUsers.length; j++) {
      if (controlledUsers[j] != null) {
        // regarder si la date en cours est > à la date enregistrée...
        Object obj = byUser.get(controlledUsers[j]);
        if (obj != null && !obj.toString().equals("Never")) {
          Date dateTab = (Date) obj;
          if (date[j].after(dateTab)) {
            byUser.put(controlledUsers[j], date[j]);
          }
          Object objNb = nbAccessbyUser.get(controlledUsers[j]);
          int nbAccess = 0;
          if (objNb != null) {
            nbAccess = (Integer) objNb;
            nbAccess = nbAccess + 1;
          }
          nbAccessbyUser.put(controlledUsers[j], nbAccess);
        } else {
          byUser.put(controlledUsers[j], date[j]);
          nbAccessbyUser.put(controlledUsers[j], 1);
        }
      }
    }

    // mise à jour de la date de dernier accès et du nombre d'accès pour les utilisateurs ayant lu
    for (final HistoryByUser historyByUser : statByUser) {
      UserDetail user = historyByUser.getUser();
      // recherche de la date de dernier accès
      Date lastAccess = byUser.get(user);
      if (lastAccess != null) {
        historyByUser.setLastAccess(lastAccess);
      }
      // retrieve access number
      Integer nbAccess = nbAccessbyUser.get(user);
      if (nbAccess != null) {
        historyByUser.setNbAccess(nbAccess);
      }
    }

    // Sort list to get readers first
    LastAccessComparatorDesc comparator = new LastAccessComparatorDesc();
    Collections.sort((List<HistoryByUser>) statByUser, comparator);

    SilverTrace.info(
        "statistic", "DefaultStatisticService.getHistoryByObject()", "root.MSG_GEN_EXIT_METHOD");
    return statByUser;
  }
  public static boolean processThumbnail(ForeignPK pk, String objectType, List<FileItem> parameters)
      throws Exception {
    boolean thumbnailChanged = false;
    String mimeType = null;
    String physicalName = null;
    FileItem uploadedFile = FileUploadUtil.getFile(parameters, "WAIMGVAR0");
    if (uploadedFile != null) {
      String logicalName = uploadedFile.getName().replace('\\', '/');
      if (StringUtil.isDefined(logicalName)) {
        logicalName = FilenameUtils.getName(logicalName);
        mimeType = FileUtil.getMimeType(logicalName);
        String type = FileRepositoryManager.getFileExtension(logicalName);
        if (FileUtil.isImage(logicalName)) {
          physicalName = String.valueOf(System.currentTimeMillis()) + '.' + type;
          SilverpeasFileDescriptor descriptor =
              new SilverpeasFileDescriptor(pk.getInstanceId())
                  .mimeType(mimeType)
                  .parentDirectory(publicationSettings.getString("imagesSubDirectory"))
                  .fileName(physicalName);
          SilverpeasFile target = SilverpeasFileProvider.newFile(descriptor);
          target.writeFrom(uploadedFile.getInputStream());
        } else {
          throw new ThumbnailRuntimeException(
              "ThumbnailController.processThumbnail()",
              SilverpeasRuntimeException.ERROR,
              "thumbnail_EX_MSG_WRONG_TYPE_ERROR");
        }
      }
    }

    // If no image have been uploaded, check if one have been picked up from a gallery
    if (physicalName == null) {
      // on a pas d'image, regarder s'il y a une provenant de la galerie
      String nameImageFromGallery = FileUploadUtil.getParameter(parameters, "valueImageGallery");
      if (StringUtil.isDefined(nameImageFromGallery)) {
        physicalName = nameImageFromGallery;
        mimeType = "image/jpeg";
      }
    }

    // If one image is defined, save it through Thumbnail service
    if (StringUtil.isDefined(physicalName)) {
      ThumbnailDetail detail =
          new ThumbnailDetail(
              pk.getInstanceId(),
              Integer.parseInt(pk.getId()),
              ThumbnailDetail.THUMBNAIL_OBJECTTYPE_PUBLICATION_VIGNETTE);
      detail.setOriginalFileName(physicalName);
      detail.setMimeType(mimeType);
      try {
        ThumbnailController.updateThumbnail(detail);
        thumbnailChanged = true;
      } catch (ThumbnailRuntimeException e) {
        SilverTrace.error(
            "thumbnail",
            "KmeliaRequestRouter.processVignette",
            "thumbnail_MSG_UPDATE_THUMBNAIL_KO",
            e);
        try {
          ThumbnailController.deleteThumbnail(detail);
        } catch (Exception exp) {

        }
      }
    }
    return thumbnailChanged;
  }