--- /dev/null
+/*******************************************************************************
+ * Copyright � Igor Barma, Alexandre Desoubeaux, Christian Martel, Eric Brun, Mathieu Amblard, Gwenael Gevet, Pierre Guillot, 2012
+ * Copyright Alexandre Desoubeaux, Christian Martel, Cedric Lecarpentier, Alexandre Lefevre, Marc Salvat 2014-2016
+ * Copyright Alexandre Desoubeaux, Christian Martel, Cedric Lecarpentier, Marc Salvat, Marc Suarez, Harifetra Ramamonjy 2017
+ *
+ * This file is part of the work and learning management system Pentila Nero.
+ *
+ * Pentila Nero is free software. You can redistribute it and/or modify since
+ * you respect the terms of either (at least one of the both license) :
+ * - under the terms of the GNU Affero General Public License as
+ * published by the Free Software Foundation, either version 3 of the
+ * License, or (at your option) any later version.
+ * - the CeCILL-C as published by CeCILL-C; either version 1 of the
+ * License, or any later version
+ * - the GNU Lesser General Public License as published by the
+ * Free Software Foundation, either version 3 of the license,
+ * or (at your option) any later version.
+ *
+ * There are special exceptions to the terms and conditions of the
+ * licenses as they are applied to this software. View the full text of
+ * the exception in file LICENSE-PROJECT.txt in the directory of this software
+ * distribution.
+ *
+ * Pentila Nero is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ * Licenses for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License
+ * and the CeCILL-C and the GNU Lesser General Public License along with
+ * Pentila Nero. If not, see :
+ * <http://www.gnu.org/licenses/> and
+ * <http://www.cecill.info/licences.fr.html>.
+ ******************************************************************************/
+package com.pentila.entSavoie.portlets.actualites;
+
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Date;
+import java.util.List;
+import java.util.ResourceBundle;
+
+import com.liferay.portal.kernel.dao.orm.Criterion;
+import com.liferay.portal.kernel.dao.orm.DynamicQuery;
+import com.liferay.portal.kernel.dao.orm.DynamicQueryFactoryUtil;
+import com.liferay.portal.kernel.dao.orm.ProjectionFactoryUtil;
+import com.liferay.portal.kernel.dao.orm.ProjectionList;
+import com.liferay.portal.kernel.dao.orm.QueryUtil;
+import com.liferay.portal.kernel.dao.orm.RestrictionsFactoryUtil;
+import com.liferay.portal.kernel.exception.PortalException;
+import com.liferay.portal.kernel.exception.SystemException;
+import com.liferay.portal.kernel.json.JSONArray;
+import com.liferay.portal.kernel.json.JSONFactoryUtil;
+import com.liferay.portal.kernel.json.JSONObject;
+import com.liferay.portal.kernel.log.Log;
+import com.liferay.portal.kernel.log.LogFactoryUtil;
+import com.liferay.portal.kernel.portlet.PortletClassLoaderUtil;
+import com.liferay.portal.kernel.repository.model.FileEntry;
+import com.liferay.portal.kernel.util.FileUtil;
+import com.liferay.portal.kernel.util.HtmlUtil;
+import com.liferay.portal.kernel.util.OrderByComparator;
+import com.liferay.portal.kernel.util.PortalClassLoaderUtil;
+import com.liferay.portal.kernel.util.PrefsPropsUtil;
+import com.liferay.portal.kernel.util.PropsKeys;
+import com.liferay.portal.kernel.workflow.WorkflowConstants;
+import com.liferay.portal.model.Group;
+import com.liferay.portal.model.Organization;
+import com.liferay.portal.model.Role;
+import com.liferay.portal.model.RoleConstants;
+import com.liferay.portal.model.User;
+import com.liferay.portal.service.GroupLocalServiceUtil;
+import com.liferay.portal.service.OrganizationLocalServiceUtil;
+import com.liferay.portal.service.RoleLocalServiceUtil;
+import com.liferay.portal.service.UserGroupRoleLocalServiceUtil;
+import com.liferay.portal.theme.ThemeDisplay;
+import com.liferay.portlet.blogs.model.BlogsEntry;
+import com.liferay.portlet.blogs.service.BlogsEntryLocalServiceUtil;
+import com.liferay.portlet.documentlibrary.service.DLAppLocalServiceUtil;
+import com.liferay.portlet.documentlibrary.util.DLPreviewableProcessor;
+import com.pentila.entSavoie.ENTDisplayUtil;
+import com.pentila.entSavoie.ENTRoleUtilFactory;
+import com.pentila.entSavoie.ENTRolesConstants;
+import com.pentila.entSavoie.blogEntryInfos.model.BlogEntryDelegate;
+import com.pentila.entSavoie.blogEntryInfos.model.BlogEntryInfos;
+import com.pentila.entSavoie.blogEntryInfos.service.BlogEntryDelegateLocalServiceUtil;
+import com.pentila.entSavoie.blogEntryInfos.service.BlogEntryInfosLocalServiceUtil;
+import com.pentila.entSavoie.blogEntryInfos.service.ConfirmReadBlogEntryLocalServiceUtil;
+import com.pentila.entSavoie.utils.BlogsEntryDateComparator;
+import com.pentila.entSavoie.utils.DLAppUtil;
+import com.pentila.entSavoie.utils.DLEntryUtil;
+import com.pentila.entSavoie.utils.ENTMainUtilsLocalServiceUtil;
+import com.pentila.entSavoie.utils.GroupCacheUtil;
+import com.pentila.entSavoie.utils.JSPPortletUtil;
+import com.pentila.entSavoie.utils.PortletConstant;
+//import com.liferay.util.dao.orm.CustomSQLUtil;
+
+public class ActuUtils {
+
+ private static Log logger = LogFactoryUtil.getLog(ActuUtils.class);
+
+ public static final String QUERY_SELECT_ALL_BLOG_ENTRIES_WITH_INFOS = "selectAllBlogEntriesWithInfos";
+ public static final String QUERY_SELECT_ALL_ACTIVE_GROUPS = "selectAllActiveGroups";
+
+ public static JSONObject getAllActu(User user, ThemeDisplay themeDisplay, long scopeGroupId, String recherche, long rechercheGrp,
+ int rechercheCateg, boolean onlyMyActus, int start, int limit,
+ boolean isAdminGrp, long entryId, boolean classic,
+ boolean highPrio, boolean headMaster) throws PortalException, SystemException {
+ return getAllActu(user, themeDisplay, scopeGroupId, recherche, rechercheGrp, rechercheCateg, onlyMyActus, start, limit, isAdminGrp, entryId, classic, highPrio, headMaster, false);
+ }
+
+ /**
+ * Main method used to fetch news
+ * @param user
+ * @param themeDisplay
+ * @param scopeGroupId
+ * @param recherche
+ * @param rechercheGrp
+ * @param rechercheCateg
+ * @param onlyMyActus
+ * @param start
+ * @param limit
+ * @param isAdminGrp
+ * @param entryId
+ * @param classic
+ * @param highPrio
+ * @param headMaster
+ * @param isWelcomePage
+ * @return
+ * @throws PortalException
+ * @throws SystemException
+ */
+ public static JSONObject getAllActu(User user, ThemeDisplay themeDisplay, long scopeGroupId, String recherche, long rechercheGrp,
+ int rechercheCateg, boolean onlyMyActus, int start, int limit,
+ boolean isAdminGrp, long entryId, boolean classic,
+ boolean highPrio, boolean headMaster, boolean isWelcomePage) throws PortalException, SystemException {
+
+ // Returned Json object
+ final JSONObject ret = JSONFactoryUtil.createJSONObject();
+ ret.put("success", true);
+
+ Date now = new Date();
+
+ // Allows to determine whether we are in the global news service or in a specific group news service
+ Group gScope = GroupLocalServiceUtil.getGroup(scopeGroupId);
+
+ List<BlogsEntry> finalBlogsEntryList = new ArrayList<BlogsEntry>();
+ List<BlogsEntry> finalHMBlogsEntryList = new ArrayList<BlogsEntry>();
+ List<BlogEntryInfos> finalBlogEntryInfosList = new ArrayList<BlogEntryInfos>();
+ List<BlogEntryInfos> finalHMBlogEntryInfosList = new ArrayList<BlogEntryInfos>();
+
+ // Define all roles
+ Role headmasterRole = ENTRoleUtilFactory.getInstance(user.getCompanyId()).getRole(ENTRolesConstants.NATIONAL_4);
+ Boolean isHeadMaster = RoleLocalServiceUtil.hasUserRole(user.getUserId(), headmasterRole.getRoleId());
+
+ Role adminGrpRole = ENTRoleUtilFactory.getInstance(user.getCompanyId()).getRole(ENTRolesConstants.GROUP_ADMIN);
+ Boolean isGrpAdmin = RoleLocalServiceUtil.hasUserRole(user.getUserId(), adminGrpRole.getRoleId());
+
+ Role student = ENTRoleUtilFactory.getInstance(user.getCompanyId()).getRole(ENTRolesConstants.NATIONAL_1);
+ Boolean isStudent = RoleLocalServiceUtil.hasUserRole(user.getUserId(), student.getRoleId());
+
+ Role parent = ENTRoleUtilFactory.getInstance(user.getCompanyId()).getRole(ENTRolesConstants.NATIONAL_2);
+ Boolean isParent = RoleLocalServiceUtil.hasUserRole(user.getUserId(), parent.getRoleId());
+
+ Role teacher = ENTRoleUtilFactory.getInstance(user.getCompanyId()).getRole(ENTRolesConstants.NATIONAL_3);
+ Boolean isTeacher = RoleLocalServiceUtil.hasUserRole(user.getUserId(), teacher.getRoleId());
+
+ Role adminRole = ENTRoleUtilFactory.getInstance(user.getCompanyId()).getRole(RoleConstants.ADMINISTRATOR);
+ Boolean isAdministrator = RoleLocalServiceUtil.hasUserRole(user.getUserId(), adminRole.getRoleId());
+
+ // Check if user is delegate for his etab
+ List<BlogEntryDelegate> listBed = BlogEntryDelegateLocalServiceUtil.getEtabUserDelegate(user.getUserId());
+ Boolean isDelegate = false;
+ if (!listBed.isEmpty()) {
+ isDelegate = true;
+ }
+
+ // Get all news
+ if(entryId == 0){
+
+ // The total list of blog entries
+ List<BlogsEntry> blogsEntryFullList = new ArrayList<BlogsEntry>();
+ List<BlogEntryInfos> blogEntryInfosList = new ArrayList<BlogEntryInfos>();
+
+ // We're already in a group (accesAteliers)
+ if(gScope.isRegularSite() || gScope.isOrganization()){
+ // get all new for this group
+ List<BlogsEntry> groupBlogEntry = new ArrayList<BlogsEntry>();
+ groupBlogEntry.addAll(
+ BlogsEntryLocalServiceUtil.getGroupEntries(scopeGroupId, WorkflowConstants.STATUS_ANY, QueryUtil.ALL_POS, QueryUtil.ALL_POS));
+ blogsEntryFullList.addAll(groupBlogEntry);
+
+ List<Long> listGroupId = new ArrayList<Long>();
+ listGroupId.add(scopeGroupId);
+
+ blogEntryInfosList.addAll(
+ getBlogEntryInfosListForGroupIdList(listGroupId, false));
+ } else {
+ // First we collect all groups we fetch news linked to
+ List<Long> globalGroupIdList = new ArrayList<Long>();
+
+// // Collect institutional groups
+// LinkedHashMap<String, Object> groupParams = new LinkedHashMap<String, Object>();
+// groupParams.put("usersGroups", new Long(user.getUserId()));
+// groupParams.put("active", Boolean.TRUE);
+// GroupNameComparator gnc = new GroupNameComparator();
+//
+// List<Group> groupList = GroupLocalServiceUtil.search(user.getCompanyId(), null, null, groupParams, QueryUtil.ALL_POS, QueryUtil.ALL_POS, gnc);
+//
+// // Filter on active groups with news enabled
+// List<Group> activeGroups = CommunityInfosLocalServiceUtil.findActiveGroupsForNews(groupList);
+// for (Group group : activeGroups) {
+// globalGroupIdList.add(group.getGroupId());
+// }
+//
+// // Collect public groups
+// List<CommunityInfos> ciIntranet = CommunityInfosLocalServiceUtil.getCommunityInfosByStatusPolitic(0, 2);
+// for (CommunityInfos ci: ciIntranet) {
+// if (!globalGroupIdList.contains(ci.getGroupId()) && ci.isIsNewsActive()) {
+// // Filter on real public groups (politics is not used anymore)
+// Group grp = GroupLocalServiceUtil.getGroup(ci.getGroupId());
+// if (grp.getType() == 0) {
+// globalGroupIdList.add(ci.getGroupId());
+// }
+// }
+// }
+//
+// // Get all non-migrated organizations with news enabled
+// List<Organization> listOrgaUserGrp = null;
+// if (isAdministrator || isDelegate || isGrpAdmin || isHeadMaster || !(isTeacher || isParent || isStudent)) {
+// listOrgaUserGrp = CommunityInfosLocalServiceUtil.findAllCollegeOrganizationWithApplications(user, "1", null, null, 0, -1, true);
+// }
+// else {
+// listOrgaUserGrp = CommunityInfosLocalServiceUtil.UserOrgsWithApplications(user, "1", null, null, 0, -1, true);
+// }
+//
+// if (!listOrgaUserGrp.isEmpty()) {
+// List<Group> orgaGroupIdList = CommunityInfosLocalServiceUtil.getOrgaGroupIds(listOrgaUserGrp);
+// for (Group grp : orgaGroupIdList){
+// if (!globalGroupIdList.contains(grp.getGroupId())) {
+// globalGroupIdList.add(grp.getGroupId());
+// }
+// }
+// }
+
+ // Use cache
+ globalGroupIdList = GroupCacheUtil.getUserGroupIdsWithNews(user, recherche);
+
+ // Get all news for all groups
+
+ // Fetch BlogsEntry objects for all groups
+ blogsEntryFullList = getBlogsEntryListForGroupIdList(globalGroupIdList);
+
+ // Fetch BlogEntryInfos objects for all groups
+ //List<BlogEntryInfos> blogEntryInfosList = BlogEntryInfosLocalServiceUtil.getBlogEntryInfosForGroupIdList(globalGroupIdList);
+ blogEntryInfosList = getBlogEntryInfosListForGroupIdList(globalGroupIdList, false);
+ }
+
+ // List of already added news id (to avoid duplicates)
+ List<Long> lbeAlreadyPut = new ArrayList<Long>();
+
+
+ for(BlogsEntry blogsEntry : blogsEntryFullList){
+
+ boolean isAuthor = blogsEntry.getUserId() == user.getUserId();
+
+ for (BlogEntryInfos bei: blogEntryInfosList) {
+ if (bei.getBlogEntryId() == blogsEntry.getEntryId()) {
+ if ((bei.getBlogEntryGroup()) == 0) {
+ finalBlogsEntryList.add(blogsEntry);
+ } else if (!lbeAlreadyPut.contains(bei.getBlogEntryGroup())){
+ // Adding the blog entry to the list is done just below
+ //finalBlogsEntryList.add(blogsEntry);
+ lbeAlreadyPut.add(bei.getBlogEntryGroup());
+ } else {
+ break;
+ }
+
+ // Check date validity and ownership
+ if (
+ (bei.getExpirationDate().after(now) && now.after(bei.getParutionDate()) || isAuthor)
+ && (
+ (isAuthor && onlyMyActus) || !onlyMyActus
+ )
+ ) {
+
+ // Get classic news (left column)
+ if (!bei.getHeadMaster() && classic){
+ finalBlogsEntryList.add(blogsEntry);
+ finalBlogEntryInfosList.add(bei);
+ continue;
+ }
+
+ // Get headmaster news (right column)
+ if (headMaster && bei.getHeadMaster()) {
+ // on ajoute dans headMaster
+ finalHMBlogsEntryList.add(blogsEntry);
+ finalHMBlogEntryInfosList.add(bei);
+ }
+ }
+ }
+ } // end loop over blogentryinfos
+ } // end loop over blogentries
+
+
+ // Sort news by descending date
+ OrderByComparator obc = new BlogsEntryDateComparator();
+ Collections.sort(finalBlogsEntryList, obc);
+ Collections.sort(finalHMBlogsEntryList, obc);
+
+ // Add list sizes to final Json object
+ ret.put("total", finalBlogsEntryList.size());
+ ret.put("totalHM", finalHMBlogsEntryList.size());
+
+ // Process sub-lists if needed
+ if (classic) {
+ if (limit>finalBlogsEntryList.size()){
+ finalBlogsEntryList = finalBlogsEntryList.subList(start, finalBlogsEntryList.size());
+ }else{
+ finalBlogsEntryList = finalBlogsEntryList.subList(start, limit);
+ }
+ }
+
+ if (headMaster) {
+ if (limit>finalHMBlogsEntryList.size()){
+ finalHMBlogsEntryList = finalHMBlogsEntryList.subList(start, finalHMBlogsEntryList.size());
+ }else{
+ finalHMBlogsEntryList = finalHMBlogsEntryList.subList(start, limit);
+ }
+ }
+
+ } else {
+ // Get a specific entryId
+ try{
+ BlogEntryInfos bei = BlogEntryInfosLocalServiceUtil.getBlogEntryInfosByBlogEntryId(entryId, QueryUtil.ALL_POS, QueryUtil.ALL_POS).get(0);
+
+ if (headMaster && bei.getHeadMaster()) {
+ ret.put("totalHM", 1);
+ finalHMBlogsEntryList.add(BlogsEntryLocalServiceUtil.getBlogsEntry(entryId));
+ finalHMBlogEntryInfosList.add(bei);
+ } else {
+ ret.put("total", 1);
+ finalBlogsEntryList.add(BlogsEntryLocalServiceUtil.getBlogsEntry(entryId));
+ finalBlogEntryInfosList.add(bei);
+ }
+ } catch (Exception e){}
+ }
+
+ boolean canEditOrg = isHeadMaster || isAdminGrp;
+
+ // Now create returned Json objects
+ JSONArray actus = JSONFactoryUtil.createJSONArray();
+ JSONArray actusHeadMaster = JSONFactoryUtil.createJSONArray();
+
+ for (BlogsEntry be : finalBlogsEntryList){
+ for (BlogEntryInfos bei : finalBlogEntryInfosList) {
+ if (be.getEntryId() == bei.getBlogEntryId()) {
+ actus = getActuAsJson(actus, be, bei, user, isAdministrator, canEditOrg, themeDisplay);
+ }
+ }
+ }
+ for (BlogsEntry be : finalHMBlogsEntryList){
+ for (BlogEntryInfos bei : finalHMBlogEntryInfosList) {
+ if (be.getEntryId() == bei.getBlogEntryId()) {
+ actusHeadMaster = getActuAsJson(actusHeadMaster, be, bei, user, isAdministrator, canEditOrg, themeDisplay);
+ }
+ }
+ }
+
+ ret.put("actualite", actus);
+ ret.put("actualiteHM", actusHeadMaster);
+
+ // Fetch high priority news
+ if (highPrio) {
+ ret.put("actualiteHP", getActuHighPrio(themeDisplay, user));
+ }
+
+ return ret;
+ }
+
+
+ /**
+ * Get the list of blog entries for a given list of group ids
+ * @param groupIdList
+ * @return
+ */
+ public static List<BlogsEntry> getBlogsEntryListForGroupIdList(List<Long> groupIdList) {
+ DynamicQuery dynamicQuery = DynamicQueryFactoryUtil.forClass(BlogsEntry.class, "be", PortalClassLoaderUtil.getClassLoader());
+ Criterion criterion = null;
+
+ for (Long groupId : groupIdList){
+ if(criterion != null){
+ criterion = RestrictionsFactoryUtil.or(criterion , RestrictionsFactoryUtil.eq("be.groupId",groupId));
+ }
+ else{
+ criterion = RestrictionsFactoryUtil.eq("be.groupId",groupId);
+ }
+ }
+
+ if (criterion == null) {
+ return new ArrayList<BlogsEntry>();
+ }
+
+ ProjectionList projectionList = ProjectionFactoryUtil.projectionList();
+ projectionList.add(ProjectionFactoryUtil.property("be.entryId"));
+ projectionList.add(ProjectionFactoryUtil.property("be.groupId"));
+ projectionList.add(ProjectionFactoryUtil.property("be.companyId"));
+ projectionList.add(ProjectionFactoryUtil.property("be.userId"));
+ projectionList.add(ProjectionFactoryUtil.property("be.userName"));
+ projectionList.add(ProjectionFactoryUtil.property("be.createDate"));
+ projectionList.add(ProjectionFactoryUtil.property("be.modifiedDate"));
+ projectionList.add(ProjectionFactoryUtil.property("be.title"));
+ projectionList.add(ProjectionFactoryUtil.property("be.urlTitle"));
+ projectionList.add(ProjectionFactoryUtil.property("be.content"));
+ projectionList.add(ProjectionFactoryUtil.property("be.displayDate"));
+ projectionList.add(ProjectionFactoryUtil.property("be.allowTrackbacks"));
+ projectionList.add(ProjectionFactoryUtil.property("be.trackbacks"));
+ projectionList.add(ProjectionFactoryUtil.property("be.allowPingbacks"));
+ projectionList.add(ProjectionFactoryUtil.property("be.status"));
+ projectionList.add(ProjectionFactoryUtil.property("be.statusByUserId"));
+ projectionList.add(ProjectionFactoryUtil.property("be.statusByUserName"));
+ projectionList.add(ProjectionFactoryUtil.property("be.statusDate"));
+ projectionList.add(ProjectionFactoryUtil.property("be.description"));
+ projectionList.add(ProjectionFactoryUtil.property("be.smallImage"));
+ projectionList.add(ProjectionFactoryUtil.property("be.smallImageId"));
+ projectionList.add(ProjectionFactoryUtil.property("be.smallImageURL"));
+ dynamicQuery.setProjection(projectionList);
+ dynamicQuery.add(criterion);
+
+ List<BlogsEntry> blogsEntryList = new ArrayList<BlogsEntry>();
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+ try {
+ //Execute the query
+ List<Object[]> objs = BlogsEntryLocalServiceUtil.dynamicQuery(dynamicQuery);
+ for (Object[] obj : objs){
+ BlogsEntry be = BlogsEntryLocalServiceUtil.createBlogsEntry((Long) obj[0]);
+ be.setGroupId((Long) obj[1]);
+ be.setCompanyId((Long) obj[2]);
+ be.setUserId(Long.valueOf(String.valueOf(obj[3])));
+ be.setUserName(String.valueOf(obj[4]));
+ be.setCreateDate(sdf.parse(String.valueOf(obj[5])));
+ be.setModifiedDate(sdf.parse(String.valueOf(obj[6])));
+ be.setTitle(String.valueOf(obj[7]));
+ be.setUrlTitle(String.valueOf(obj[8]));
+ be.setContent(String.valueOf(obj[9]));
+ be.setDisplayDate(sdf.parse(String.valueOf(obj[10])));
+ be.setAllowTrackbacks((Boolean) obj[11]);
+ be.setTrackbacks(String.valueOf(obj[12]));
+ be.setAllowPingbacks((Boolean) obj[13]);
+ be.setStatus((Integer) obj[14]);
+ be.setStatusByUserId((Long) obj[15]);
+ be.setStatusByUserName(String.valueOf(obj[16]));
+ be.setStatusDate(sdf.parse(String.valueOf(obj[17])));
+ be.setDescription(String.valueOf(obj[18]));
+ be.setSmallImage((Boolean) obj[19]);
+ be.setSmallImageId((Long) obj[20]);
+ be.setSmallImageURL(String.valueOf(obj[21]));
+ blogsEntryList.add(be);
+ }
+ } catch (Exception e) {
+ logger.error(e);
+ }
+ return blogsEntryList;
+ }
+
+ /**
+ * Get the list of blog entries for a given list of group ids
+ * @param groupIdList
+ * @return
+ */
+ public static List<BlogEntryInfos> getBlogEntryInfosListForGroupIdList(List<Long> groupIdList, boolean isHighPrio) {
+ DynamicQuery dynamicQuery = DynamicQueryFactoryUtil.forClass(BlogEntryInfos.class, "bei", PortletClassLoaderUtil.getClassLoader());
+ Criterion globalCriterion = null;
+ Criterion groupIdCriterion = null;
+
+ for (Long groupId : groupIdList){
+ if(groupIdCriterion != null){
+ groupIdCriterion = RestrictionsFactoryUtil.or(groupIdCriterion , RestrictionsFactoryUtil.eq("bei.groupId",groupId));
+ }
+ else{
+ groupIdCriterion = RestrictionsFactoryUtil.eq("bei.groupId",groupId);
+ }
+ }
+
+ if (groupIdCriterion == null) {
+ return new ArrayList<BlogEntryInfos>();
+ }
+
+ // Filter on high priority blog entryinfos if needed
+ if (isHighPrio) {
+ globalCriterion = RestrictionsFactoryUtil.and(groupIdCriterion , RestrictionsFactoryUtil.eq("bei.highPriority",true));
+ } else {
+ globalCriterion = groupIdCriterion;
+ }
+
+ ProjectionList projectionList = ProjectionFactoryUtil.projectionList();
+ projectionList.add(ProjectionFactoryUtil.property("bei.blogEntryInfosId"));
+ projectionList.add(ProjectionFactoryUtil.property("bei.blogEntryId"));
+ projectionList.add(ProjectionFactoryUtil.property("bei.headMaster"));
+ projectionList.add(ProjectionFactoryUtil.property("bei.highPriority"));
+ projectionList.add(ProjectionFactoryUtil.property("bei.groupId"));
+ projectionList.add(ProjectionFactoryUtil.property("bei.expirationDate"));
+ projectionList.add(ProjectionFactoryUtil.property("bei.parutionDate"));
+ projectionList.add(ProjectionFactoryUtil.property("bei.categorie"));
+ projectionList.add(ProjectionFactoryUtil.property("bei.imageId"));
+ projectionList.add(ProjectionFactoryUtil.property("bei.blogEntryGroup"));
+ projectionList.add(ProjectionFactoryUtil.property("bei.flashFileState"));
+ projectionList.add(ProjectionFactoryUtil.property("bei.intranetNews"));
+ projectionList.add(ProjectionFactoryUtil.property("bei.lastEditorId"));
+ projectionList.add(ProjectionFactoryUtil.property("bei.priority"));
+ dynamicQuery.setProjection(projectionList);
+ dynamicQuery.add(globalCriterion);
+
+ List<BlogEntryInfos> blogEntryInfosList = new ArrayList<BlogEntryInfos>();
+ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+ try {
+ //Execute the query
+ List<Object[]> objs = BlogEntryInfosLocalServiceUtil.dynamicQuery(dynamicQuery);
+ for (Object[] obj : objs){
+ BlogEntryInfos bei = BlogEntryInfosLocalServiceUtil.createBlogEntryInfos((Long) obj[0]);
+ bei.setBlogEntryId((Long) obj[1]);
+ bei.setHeadMaster((Boolean) obj[2]);
+ bei.setHighPriority((Boolean) obj[3]);
+ bei.setGroupId((Long) obj[4]);
+ bei.setExpirationDate(sdf.parse(String.valueOf(obj[5])));
+ bei.setParutionDate(sdf.parse(String.valueOf(obj[6])));
+ bei.setCategorie((Integer) obj[7]);
+ bei.setImageId((Long) obj[8]);
+ bei.setBlogEntryGroup((Long) obj[9]);
+ bei.setFlashFileState(String.valueOf(obj[10]));
+ bei.setIntranetNews((Boolean) obj[11]);
+ bei.setLastEditorId((Long) obj[12]);
+ bei.setPriority((Boolean) obj[13]);
+ blogEntryInfosList.add(bei);
+ }
+ } catch (Exception e) {
+ logger.error(e);
+ }
+ return blogEntryInfosList;
+ }
+
+
+ /**
+ * This method builds a JSON Array for each news
+ * @param actus : the returned Json array
+ * @param blogsEntry :
+ * @param blogEntryInfos
+ * @param user
+ * @param hasAdminRole
+ * @param canEditOrg
+ * @param themeDisplay
+ * @return
+ * @throws SystemException
+ * @throws PortalException
+ */
+ public static JSONArray getActuAsJson(JSONArray actus, BlogsEntry blogsEntry, BlogEntryInfos blogEntryInfos, User user, boolean isAdministrator, boolean canEditOrg, ThemeDisplay themeDisplay) throws SystemException, PortalException {
+
+ Date now = new Date();
+ ResourceBundle messages = ResourceBundle.getBundle("content.Language", user.getLocale());
+ SimpleDateFormat classicDateFormat = new SimpleDateFormat("dd-MM-yyyy '" + messages.getString("a") + "' HH:mm");
+ SimpleDateFormat sortDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
+
+ Group grp = GroupLocalServiceUtil.getGroup(blogEntryInfos.getGroupId());
+ String grpName = grp.getDescriptiveName();
+
+ boolean isAdmin = false;
+ boolean isAuthor = (blogsEntry.getUserId() == user.getUserId());
+
+ // Does the user have the rights to edit/delete the news ?
+ boolean isHidden = true;
+ if (grp.isRegularSite()) {
+
+ Role communityAdminRole = ENTRoleUtilFactory.getInstance(user.getCompanyId()).getRole(RoleConstants.SITE_ADMINISTRATOR);
+ Role communityOwnerRole = ENTRoleUtilFactory.getInstance(user.getCompanyId()).getRole(RoleConstants.SITE_OWNER);
+
+ isAdmin = UserGroupRoleLocalServiceUtil.hasUserGroupRole(user.getUserId(), blogsEntry.getGroupId(), communityAdminRole.getRoleId()) ||
+ UserGroupRoleLocalServiceUtil.hasUserGroupRole(user.getUserId(), blogsEntry.getGroupId(), communityOwnerRole.getRoleId());
+
+ grpName = grp.getName();
+
+ if (isAuthor || isAdmin || isAdministrator){
+ isHidden = false;
+ }
+
+ }
+ else if (grp.isOrganization()) {
+
+ grpName = ENTDisplayUtil.formatSCONETName(user, grp.getName());
+
+ if (isAuthor || isAdministrator || canEditOrg){
+ isHidden = false;
+ }
+ }
+
+ boolean unActive = false;
+ if (now.after(blogEntryInfos.getExpirationDate()) || blogEntryInfos.getParutionDate().after(now)) {
+ unActive = true;
+ }
+
+ String resume = ellipsise(HtmlUtil.extractText(blogsEntry.getContent()), 250);
+
+ JSONObject actualite = JSONFactoryUtil.createJSONObject();
+ actualite.put("blogEntryId", blogsEntry.getEntryId());
+ actualite.put("blogEntryInfosId", blogEntryInfos.getBlogEntryInfosId());
+ actualite.put("date", messages.getString("le") + " " +classicDateFormat.format(blogsEntry.getDisplayDate()));
+ actualite.put("dateSort", sortDateFormat.format(blogsEntry.getDisplayDate()));
+ actualite.put("timemillis", blogsEntry.getDisplayDate().getTime());
+ actualite.put("title",blogsEntry.getTitle());
+ actualite.put("author", blogsEntry.getUserName());
+ actualite.put("isAuthor", isAuthor);
+ actualite.put("content", resume);
+ actualite.put("grpName", grpName.replace(" LFR_ORGANIZATION", ""));
+ actualite.put("hideControl", isHidden);
+ actualite.put("intranetNews", blogEntryInfos.isIntranetNews());
+ actualite.put("imageId", blogEntryInfos.getImageId());
+ actualite.put("unActive", unActive);
+ actualite.put("isHighPrio", blogEntryInfos.isHighPriority());
+ actualite.put("isPrio", blogEntryInfos.isPriority());
+
+ // Add image, attachements and flash files
+ if (themeDisplay != null) {
+ if (blogEntryInfos.getImageId()!=0){
+ try {
+ FileEntry fe = DLAppLocalServiceUtil.getFileEntry(blogEntryInfos.getImageId());
+ actualite.put("urlThumb", DLAppUtil.getImageSrc(fe, themeDisplay, DLPreviewableProcessor.THUMBNAIL_INDEX_DEFAULT));
+ actualite.put("height", PrefsPropsUtil.getInteger(PropsKeys.DL_FILE_ENTRY_THUMBNAIL_MAX_HEIGHT));
+ actualite.put("width", PrefsPropsUtil.getInteger(PropsKeys.DL_FILE_ENTRY_THUMBNAIL_MAX_WIDTH));
+ } catch (Exception e){
+ // Image deleted
+ }
+ }
+
+
+ // Attached files
+ final JSONArray attachements = JSONFactoryUtil.createJSONArray();
+ String[] attachementsFiles = BlogEntryInfosLocalServiceUtil.getAttachmentsFiles(blogsEntry.getCompanyId(), blogEntryInfos);
+ Boolean[] params = {true, false};
+ for (int k = 0; k < attachementsFiles.length; k++) {
+ // Catch exceptions here because some weird things might happen while getting file on the filesystem
+ // And we do not want to paralyze the news print
+ try {
+ final JSONObject fileDescriptor = JSPPortletUtil.formatAttachment(themeDisplay, attachementsFiles[k], blogEntryInfos.getBlogEntryInfosId(), PortletConstant.ACTUALITES, params);
+ attachements.put(fileDescriptor);
+ } catch (Exception e) {
+ logger.info("Error while getting attachment for blogEntryInfosId "+blogEntryInfos.getBlogEntryInfosId());
+ continue;
+ }
+ }
+ actualite.put("attachements", attachements.toString());
+
+ boolean hasFlashFile = blogEntryInfos.getFlashFileState().equals(ENTMainUtilsLocalServiceUtil.getFlashFileStateConvert(user.getCompanyId())) ||
+ blogEntryInfos.getFlashFileState().equals(ENTMainUtilsLocalServiceUtil.getFlashFileStateError(user.getCompanyId()));
+ String flashFile = "";
+ String extension = "";
+ if(hasFlashFile){
+ try{
+ String fileName = FileUtil.getShortFileName(BlogEntryInfosLocalServiceUtil.getFlashFile(blogsEntry.getCompanyId(), blogEntryInfos));
+ String[] splitFN = DLEntryUtil.splitFileName(fileName);
+ extension = splitFN[1];
+
+ flashFile = themeDisplay.getPathMain()+"/blog_entries/get_blog_entry_flash_file?blogEntryInfosId="+blogEntryInfos.getBlogEntryInfosId()+"&flashFile="+fileName;
+ } catch (Exception e){
+ flashFile = "";
+ extension = "";
+ }
+ } else if(blogEntryInfos.getFlashFileState().equals(ENTMainUtilsLocalServiceUtil.getFlashFileStateProgress(user.getCompanyId()))){
+ flashFile = ENTMainUtilsLocalServiceUtil.getFlashFileStateProgress(user.getCompanyId());
+ }
+ actualite.put("flashFile", flashFile);
+ actualite.put("flashFileExtension", extension);
+
+ actus.put(actualite);
+ }
+ return actus;
+
+ }
+
+
+ /**
+ * Fetch the list of high priority news
+ * @param themeDisplay
+ * @param user
+ * @return
+ * @throws SystemException
+ * @throws PortalException
+ */
+ static JSONObject getActuHighPrio(ThemeDisplay themeDisplay, User user) throws SystemException, PortalException {
+
+ SimpleDateFormat classicDateFormatCrea = new SimpleDateFormat("dd-MM-yyyy \u00E0 HH:mm");
+
+ ResourceBundle messages = ResourceBundle.getBundle("content.Language", user.getLocale());
+ JSONObject result = JSONFactoryUtil.createJSONObject();
+
+// List<Organization> listOrgaUserGrp = user.getOrganizations();
+// List<BlogEntryInfos> listResult = new ArrayList<BlogEntryInfos>();
+// List<BlogEntryInfos> listResultFiltered = new ArrayList<BlogEntryInfos>();
+//
+// LinkedHashMap<String, Object> groupParams = new LinkedHashMap<String, Object>();
+// groupParams.put("usersGroups", new Long(user.getUserId()));
+// groupParams.put("active", Boolean.TRUE);
+// GroupNameComparator gnc = new GroupNameComparator();
+//
+// List<Group> groupList = GroupLocalServiceUtil.search(user.getCompanyId(), null, null, groupParams, QueryUtil.ALL_POS, QueryUtil.ALL_POS, gnc);
+//
+// List<Group> activeGroups = CommunityInfosLocalServiceUtil.findActiveGroupsForNews(groupList);
+// List<Long> listUserGrpIds = new ArrayList<Long>();
+// for (Group group : activeGroups) {
+// listUserGrpIds.add(group.getGroupId());
+// }
+
+// // Organizations
+// for (Organization orga : listOrgaUserGrp){
+//
+// // on teste pour ne pas prendre les orgs migrate=done
+// PortletPreferences prefs = orga.getPreferences();
+// if (prefs.getValue("migrate", "none").equals("done")) {
+// continue;
+// }
+//
+// Group g = GroupLocalServiceUtil.getGroup(orga.getGroup().getGroupId());
+//
+// List<BlogEntryInfos> listResultTmp = BlogEntryInfosLocalServiceUtil.getBlogEntryInfosByHighPriorityGrpId(g.getGroupId(), QueryUtil.ALL_POS, QueryUtil.ALL_POS, null);
+// for(BlogEntryInfos bi : listResultTmp){
+// listResult.add(bi);
+// }
+// }
+
+ List<Long> listUserGrpIds = GroupCacheUtil.getUserGroupIdsWithNews(user, "");
+
+ // Get blog entry infos of high priority news
+ List<BlogEntryInfos> listResult = getBlogEntryInfosListForGroupIdList(listUserGrpIds, true);
+
+
+ // Filter on blog entry group to avoid duplicates
+ List<BlogEntryInfos> listResultFiltered = new ArrayList<BlogEntryInfos>();
+ for (BlogEntryInfos bei : listResult){
+ if(listResultFiltered.size() > 0){
+ boolean groupBlogEntryFound = false;
+ for(BlogEntryInfos beiFiltered : listResultFiltered){
+ if(bei.getBlogEntryGroup() == beiFiltered.getBlogEntryGroup()){
+ groupBlogEntryFound = true;
+ break;
+ }
+ }
+ if(!groupBlogEntryFound){
+ //only get the master blog entry of each group actu
+ List<BlogEntryInfos> blogEntryMasters = BlogEntryInfosLocalServiceUtil.getBlogEntryInfosByBlogEntryId(bei.getBlogEntryGroup(), QueryUtil.ALL_POS, QueryUtil.ALL_POS);
+ // only one result 1 blog entry infos is attach to 1 blog entry
+ listResultFiltered.add(blogEntryMasters.get(0));
+ }
+ }
+ else{
+ //only get the master blog entry of each group actu
+ List<BlogEntryInfos> blogEntryMasters = BlogEntryInfosLocalServiceUtil.getBlogEntryInfosByBlogEntryId(bei.getBlogEntryGroup(), QueryUtil.ALL_POS, QueryUtil.ALL_POS);
+ listResultFiltered.add(blogEntryMasters.get(0));
+ }
+
+ }
+
+ Date now = new Date();
+ for (BlogEntryInfos bei : listResultFiltered){
+
+ boolean isNewsDisplayed = bei.getExpirationDate().after(now) && now.after(bei.getParutionDate());
+ if(!ConfirmReadBlogEntryLocalServiceUtil.isConfirmReadBlogEntryByBlogEntryInfosId_UserId(bei.getBlogEntryInfosId(), user.getUserId()) && isNewsDisplayed){
+
+ //on recupere les infos de l'actu
+ BlogsEntry be = BlogsEntryLocalServiceUtil.getEntry(bei.getBlogEntryId());
+
+ List<Long> listGroupIds = BlogEntryInfosLocalServiceUtil.getGroupIds(bei.getBlogEntryGroup());
+
+ String grpName="";
+
+ for(long grpId: listGroupIds){
+ Group gp = GroupLocalServiceUtil.getGroup(grpId);
+ if (gp.isOrganization()){
+ Organization org = OrganizationLocalServiceUtil.getOrganization(gp.getOrganizationId());
+ if(!grpName.equals("")){
+ grpName+= ", " + ENTDisplayUtil.formatSCONETName(user, org.getName());
+ } else {
+ grpName+= ENTDisplayUtil.formatSCONETName(user, org.getName());
+ }
+ }else{
+ if(!grpName.equals("")){
+ grpName+= ", " + gp.getName();
+ } else {
+ grpName+= gp.getName();
+ }
+ }
+ }
+
+ String[] listCateg = {messages.getString("pas-de-categorie"), messages.getString("vie-scolaire"),
+ messages.getString("vie-de-classe"), messages.getString("examens"),
+ messages.getString("loisir"), messages.getString("culture"),
+ messages.getString("cantine"), messages.getString("cdi"),
+ messages.getString("inscriptions"), messages.getString("unss")};
+
+
+
+ result.put("title", be.getTitle());
+ result.put("content", be.getContent());
+ result.put("grpName",grpName);
+ result.put("author",be.getUserName());
+ result.put("categName", listCateg[bei.getCategorie()]);
+ result.put("creaDate", messages.getString("le") + " " + classicDateFormatCrea.format(be.getCreateDate()));
+
+ result.put("imageId", bei.getImageId());
+
+ if (themeDisplay != null) {
+ if (bei.getImageId()!=0){
+ try {
+ FileEntry fe = DLAppLocalServiceUtil.getFileEntry(bei.getImageId());
+ result.put("urlThumb", DLAppUtil.getImageSrc(fe, themeDisplay, DLPreviewableProcessor.THUMBNAIL_INDEX_DEFAULT));
+ result.put("height", PrefsPropsUtil.getInteger(PropsKeys.DL_FILE_ENTRY_THUMBNAIL_MAX_HEIGHT));
+ result.put("width", PrefsPropsUtil.getInteger(PropsKeys.DL_FILE_ENTRY_THUMBNAIL_MAX_WIDTH));
+
+ result.put("urlLarge", DLAppUtil.getImageSrc(fe, themeDisplay, DLPreviewableProcessor.THUMBNAIL_INDEX_CUSTOM_1));
+ result.put("largeHeight", PrefsPropsUtil.getInteger(PropsKeys.DL_FILE_ENTRY_THUMBNAIL_CUSTOM_1_MAX_HEIGHT));
+ result.put("largeWidth", PrefsPropsUtil.getInteger(PropsKeys.DL_FILE_ENTRY_THUMBNAIL_CUSTOM_1_MAX_WIDTH));
+ } catch (Exception e){
+ // Image deleted
+ }
+ }
+
+ // Pieces jointes
+ final JSONArray attachements = JSONFactoryUtil.createJSONArray();
+ String[] attachementsFiles = BlogEntryInfosLocalServiceUtil.getAttachmentsFiles(user.getCompanyId(), bei);
+ Boolean[] params = {false, true};
+ for (int k = 0; k < attachementsFiles.length; k++) {
+ final JSONObject fileDescriptor = JSPPortletUtil.formatAttachment(themeDisplay, attachementsFiles[k], bei.getBlogEntryInfosId(), PortletConstant.ACTUALITES, params);
+ attachements.put(fileDescriptor);
+ }
+ result.put("attachements", attachements.toString());
+
+ boolean hasFlashFile = bei.getFlashFileState().equals(ENTMainUtilsLocalServiceUtil.getFlashFileStateConvert(user.getCompanyId())) ||
+ bei.getFlashFileState().equals(ENTMainUtilsLocalServiceUtil.getFlashFileStateError(user.getCompanyId()));
+
+ String flashFile = "";
+ String urlFlashFile = "";
+ String extension = "";
+
+ if(hasFlashFile){
+ try{
+ flashFile = FileUtil.getShortFileName(BlogEntryInfosLocalServiceUtil.getFlashFile(user.getCompanyId(), bei));
+ String[] splitFN = DLEntryUtil.splitFileName(flashFile);
+ extension = splitFN[1];
+ urlFlashFile = themeDisplay.getPathMain()+"/blog_entries/get_blog_entry_flash_file?blogEntryInfosId="+bei.getBlogEntryInfosId()+"&flashFile="+flashFile;
+ } catch(Exception e){
+ flashFile = "";
+ extension = "";
+ urlFlashFile = "";
+ }
+ } else if(bei.getFlashFileState().equals(ENTMainUtilsLocalServiceUtil.getFlashFileStateProgress(user.getCompanyId()))){
+ flashFile = ENTMainUtilsLocalServiceUtil.getFlashFileStateProgress(user.getCompanyId());
+ }
+ result.put("flashFile", flashFile);
+ result.put("flashFileExtension", extension);
+ result.put("urlFlashFile", urlFlashFile);
+ }
+
+ // set only to the master blog entry because it is the only one checked
+ ConfirmReadBlogEntryLocalServiceUtil.addConfirmReadBlogEntry(bei.getBlogEntryInfosId(), user.getUserId());
+
+ break;
+ }
+ }
+
+ return result;
+ }
+
+
+ /**
+ * Method used to shorten string and add '...' at the end of it
+ * @param input
+ * @param maxLen
+ * @return
+ */
+ public static String ellipsise (String input, int maxLen) {
+ if (input == null)
+ return null;
+ if ((input.length() < maxLen) || (maxLen < 3))
+ return input;
+ return input.substring (0, maxLen - 3) + "...";
+ }
+
+
+}