001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portlet.usersadmin.action;
016    
017    import com.liferay.portal.kernel.bean.BeanPropertiesUtil;
018    import com.liferay.portal.kernel.dao.orm.QueryUtil;
019    import com.liferay.portal.kernel.search.Hits;
020    import com.liferay.portal.kernel.search.Sort;
021    import com.liferay.portal.kernel.servlet.ServletResponseUtil;
022    import com.liferay.portal.kernel.servlet.SessionErrors;
023    import com.liferay.portal.kernel.util.ArrayUtil;
024    import com.liferay.portal.kernel.util.CSVUtil;
025    import com.liferay.portal.kernel.util.ContentTypes;
026    import com.liferay.portal.kernel.util.OrderByComparator;
027    import com.liferay.portal.kernel.util.ParamUtil;
028    import com.liferay.portal.kernel.util.ProgressTracker;
029    import com.liferay.portal.kernel.util.StringBundler;
030    import com.liferay.portal.kernel.util.StringPool;
031    import com.liferay.portal.model.User;
032    import com.liferay.portal.security.permission.ActionKeys;
033    import com.liferay.portal.security.permission.PermissionChecker;
034    import com.liferay.portal.service.UserLocalServiceUtil;
035    import com.liferay.portal.service.permission.PortalPermissionUtil;
036    import com.liferay.portal.service.permission.PortletPermissionUtil;
037    import com.liferay.portal.struts.ActionConstants;
038    import com.liferay.portal.struts.PortletAction;
039    import com.liferay.portal.theme.ThemeDisplay;
040    import com.liferay.portal.util.PortalUtil;
041    import com.liferay.portal.util.PortletKeys;
042    import com.liferay.portal.util.PropsValues;
043    import com.liferay.portal.util.WebKeys;
044    import com.liferay.portlet.ActionResponseImpl;
045    import com.liferay.portlet.expando.model.ExpandoBridge;
046    import com.liferay.portlet.usersadmin.search.UserSearch;
047    import com.liferay.portlet.usersadmin.search.UserSearchTerms;
048    import com.liferay.portlet.usersadmin.util.UsersAdminUtil;
049    
050    import java.util.Collections;
051    import java.util.LinkedHashMap;
052    import java.util.List;
053    
054    import javax.portlet.ActionRequest;
055    import javax.portlet.ActionResponse;
056    import javax.portlet.PortletConfig;
057    import javax.portlet.PortletURL;
058    
059    import javax.servlet.http.HttpServletRequest;
060    import javax.servlet.http.HttpServletResponse;
061    
062    import org.apache.struts.action.ActionForm;
063    import org.apache.struts.action.ActionMapping;
064    
065    /**
066     * @author Brian Wing Shun Chan
067     * @author Mika Koivisto
068     */
069    public class ExportUsersAction extends PortletAction {
070    
071            @Override
072            public void processAction(
073                            ActionMapping actionMapping, ActionForm actionForm,
074                            PortletConfig portletConfig, ActionRequest actionRequest,
075                            ActionResponse actionResponse)
076                    throws Exception {
077    
078                    try {
079                            String csv = getUsersCSV(actionRequest, actionResponse);
080    
081                            String fileName = "users.csv";
082                            byte[] bytes = csv.getBytes();
083    
084                            HttpServletRequest request = PortalUtil.getHttpServletRequest(
085                                    actionRequest);
086                            HttpServletResponse response = PortalUtil.getHttpServletResponse(
087                                    actionResponse);
088    
089                            ServletResponseUtil.sendFile(
090                                    request, response, fileName, bytes, ContentTypes.TEXT_CSV_UTF8);
091    
092                            setForward(actionRequest, ActionConstants.COMMON_NULL);
093                    }
094                    catch (Exception e) {
095                            SessionErrors.add(actionRequest, e.getClass());
096    
097                            setForward(actionRequest, "portlet.users_admin.error");
098                    }
099            }
100    
101            protected String getUserCSV(User user) {
102                    StringBundler sb = new StringBundler(
103                            PropsValues.USERS_EXPORT_CSV_FIELDS.length * 2);
104    
105                    for (int i = 0; i < PropsValues.USERS_EXPORT_CSV_FIELDS.length; i++) {
106                            String field = PropsValues.USERS_EXPORT_CSV_FIELDS[i];
107    
108                            if (field.equals("fullName")) {
109                                    sb.append(CSVUtil.encode(user.getFullName()));
110                            }
111                            else if (field.startsWith("expando:")) {
112                                    String attributeName = field.substring(8);
113    
114                                    ExpandoBridge expandoBridge = user.getExpandoBridge();
115    
116                                    sb.append(
117                                            CSVUtil.encode(expandoBridge.getAttribute(attributeName)));
118                            }
119                            else {
120                                    sb.append(
121                                            CSVUtil.encode(BeanPropertiesUtil.getString(user, field)));
122                            }
123    
124                            if ((i + 1) < PropsValues.USERS_EXPORT_CSV_FIELDS.length) {
125                                    sb.append(StringPool.COMMA);
126                            }
127                    }
128    
129                    sb.append(StringPool.NEW_LINE);
130    
131                    return sb.toString();
132            }
133    
134            protected List<User> getUsers(
135                            ActionRequest actionRequest, ActionResponse actionResponse)
136                    throws Exception {
137    
138                    ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(
139                            WebKeys.THEME_DISPLAY);
140    
141                    PermissionChecker permissionChecker =
142                            themeDisplay.getPermissionChecker();
143    
144                    boolean exportAllUsers = PortalPermissionUtil.contains(
145                            permissionChecker, ActionKeys.EXPORT_USER);
146    
147                    if (!exportAllUsers &&
148                            !PortletPermissionUtil.contains(
149                                    permissionChecker, PortletKeys.USERS_ADMIN,
150                                    ActionKeys.EXPORT_USER)) {
151    
152                            return Collections.emptyList();
153                    }
154    
155                    PortletURL portletURL =
156                            ((ActionResponseImpl)actionResponse).createRenderURL(
157                                    PortletKeys.USERS_ADMIN);
158    
159                    UserSearch userSearch = new UserSearch(actionRequest, portletURL);
160    
161                    UserSearchTerms searchTerms =
162                            (UserSearchTerms)userSearch.getSearchTerms();
163    
164                    LinkedHashMap<String, Object> params =
165                            new LinkedHashMap<String, Object>();
166    
167                    long organizationId = searchTerms.getOrganizationId();
168    
169                    if (organizationId > 0) {
170                            params.put("usersOrgs", new Long(organizationId));
171                    }
172                    else if (!exportAllUsers) {
173                            User user = themeDisplay.getUser();
174    
175                            Long[] organizationIds = ArrayUtil.toArray(
176                                    user.getOrganizationIds(true));
177    
178                            if (organizationIds.length > 0) {
179                                    params.put("usersOrgs", organizationIds);
180                            }
181                    }
182    
183                    long roleId = searchTerms.getRoleId();
184    
185                    if (roleId > 0) {
186                            params.put("usersRoles", new Long(roleId));
187                    }
188    
189                    long userGroupId = searchTerms.getUserGroupId();
190    
191                    if (userGroupId > 0) {
192                            params.put("usersUserGroups", new Long(userGroupId));
193                    }
194    
195                    if (PropsValues.USERS_INDEXER_ENABLED &&
196                            PropsValues.USERS_SEARCH_WITH_INDEX) {
197    
198                            params.put("expandoAttributes", searchTerms.getKeywords());
199    
200                            Hits hits = null;
201    
202                            if (searchTerms.isAdvancedSearch()) {
203                                    hits = UserLocalServiceUtil.search(
204                                            themeDisplay.getCompanyId(), searchTerms.getFirstName(),
205                                            searchTerms.getMiddleName(), searchTerms.getLastName(),
206                                            searchTerms.getScreenName(), searchTerms.getEmailAddress(),
207                                            searchTerms.getStatus(), params,
208                                            searchTerms.isAndOperator(), QueryUtil.ALL_POS,
209                                            QueryUtil.ALL_POS, (Sort)null);
210                            }
211                            else {
212                                    hits = UserLocalServiceUtil.search(
213                                            themeDisplay.getCompanyId(), searchTerms.getKeywords(),
214                                            searchTerms.getStatus(), params, QueryUtil.ALL_POS,
215                                            QueryUtil.ALL_POS, (Sort)null);
216                            }
217    
218                            return UsersAdminUtil.getUsers(hits);
219                    }
220    
221                    if (searchTerms.isAdvancedSearch()) {
222                            return UserLocalServiceUtil.search(
223                                    themeDisplay.getCompanyId(), searchTerms.getFirstName(),
224                                    searchTerms.getMiddleName(), searchTerms.getLastName(),
225                                    searchTerms.getScreenName(), searchTerms.getEmailAddress(),
226                                    searchTerms.getStatus(), params, searchTerms.isAndOperator(),
227                                    QueryUtil.ALL_POS, QueryUtil.ALL_POS,
228                                    (OrderByComparator<User>)null);
229                    }
230                    else {
231                            return UserLocalServiceUtil.search(
232                                    themeDisplay.getCompanyId(), searchTerms.getKeywords(),
233                                    searchTerms.getStatus(), params, QueryUtil.ALL_POS,
234                                    QueryUtil.ALL_POS, (OrderByComparator<User>)null);
235                    }
236            }
237    
238            protected String getUsersCSV(
239                            ActionRequest actionRequest, ActionResponse actionResponse)
240                    throws Exception {
241    
242                    List<User> users = getUsers(actionRequest, actionResponse);
243    
244                    if (users.isEmpty()) {
245                            return StringPool.BLANK;
246                    }
247    
248                    String exportProgressId = ParamUtil.getString(
249                            actionRequest, "exportProgressId");
250    
251                    ProgressTracker progressTracker = new ProgressTracker(exportProgressId);
252    
253                    progressTracker.start(actionRequest);
254    
255                    int percentage = 10;
256                    int total = users.size();
257    
258                    progressTracker.setPercent(percentage);
259    
260                    StringBundler sb = new StringBundler(users.size());
261    
262                    for (int i = 0; i < users.size(); i++ ) {
263                            User user = users.get(i);
264    
265                            sb.append(getUserCSV(user));
266    
267                            percentage = Math.min(10 + (i * 90) / total, 99);
268    
269                            progressTracker.setPercent(percentage);
270                    }
271    
272                    progressTracker.finish(actionRequest);
273    
274                    return sb.toString();
275            }
276    
277    }