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.servlet.ServletResponseUtil;
020    import com.liferay.portal.kernel.servlet.SessionErrors;
021    import com.liferay.portal.kernel.util.ArrayUtil;
022    import com.liferay.portal.kernel.util.CSVUtil;
023    import com.liferay.portal.kernel.util.ContentTypes;
024    import com.liferay.portal.kernel.util.OrderByComparator;
025    import com.liferay.portal.kernel.util.ParamUtil;
026    import com.liferay.portal.kernel.util.ProgressTracker;
027    import com.liferay.portal.kernel.util.StringBundler;
028    import com.liferay.portal.kernel.util.StringPool;
029    import com.liferay.portal.model.User;
030    import com.liferay.portal.security.permission.ActionKeys;
031    import com.liferay.portal.security.permission.PermissionChecker;
032    import com.liferay.portal.service.UserLocalServiceUtil;
033    import com.liferay.portal.service.permission.PortalPermissionUtil;
034    import com.liferay.portal.service.permission.PortletPermissionUtil;
035    import com.liferay.portal.struts.ActionConstants;
036    import com.liferay.portal.struts.PortletAction;
037    import com.liferay.portal.theme.ThemeDisplay;
038    import com.liferay.portal.util.PortalUtil;
039    import com.liferay.portal.util.PortletKeys;
040    import com.liferay.portal.util.PropsValues;
041    import com.liferay.portal.util.WebKeys;
042    import com.liferay.portlet.ActionResponseImpl;
043    import com.liferay.portlet.expando.model.ExpandoBridge;
044    import com.liferay.portlet.usersadmin.search.UserSearch;
045    import com.liferay.portlet.usersadmin.search.UserSearchTerms;
046    
047    import java.util.Collections;
048    import java.util.LinkedHashMap;
049    import java.util.List;
050    
051    import javax.portlet.ActionRequest;
052    import javax.portlet.ActionResponse;
053    import javax.portlet.PortletConfig;
054    import javax.portlet.PortletURL;
055    
056    import javax.servlet.http.HttpServletRequest;
057    import javax.servlet.http.HttpServletResponse;
058    
059    import org.apache.struts.action.ActionForm;
060    import org.apache.struts.action.ActionMapping;
061    
062    /**
063     * @author Brian Wing Shun Chan
064     * @author Mika Koivisto
065     */
066    public class ExportUsersAction extends PortletAction {
067    
068            @Override
069            public void processAction(
070                            ActionMapping actionMapping, ActionForm actionForm,
071                            PortletConfig portletConfig, ActionRequest actionRequest,
072                            ActionResponse actionResponse)
073                    throws Exception {
074    
075                    try {
076                            String csv = getUsersCSV(actionRequest, actionResponse);
077    
078                            String fileName = "users.csv";
079                            byte[] bytes = csv.getBytes();
080    
081                            HttpServletRequest request = PortalUtil.getHttpServletRequest(
082                                    actionRequest);
083                            HttpServletResponse response = PortalUtil.getHttpServletResponse(
084                                    actionResponse);
085    
086                            ServletResponseUtil.sendFile(
087                                    request, response, fileName, bytes, ContentTypes.TEXT_CSV_UTF8);
088    
089                            setForward(actionRequest, ActionConstants.COMMON_NULL);
090                    }
091                    catch (Exception e) {
092                            SessionErrors.add(actionRequest, e.getClass());
093    
094                            setForward(actionRequest, "portlet.users_admin.error");
095                    }
096            }
097    
098            protected String getUserCSV(User user) {
099                    StringBundler sb = new StringBundler(
100                            PropsValues.USERS_EXPORT_CSV_FIELDS.length * 2);
101    
102                    for (int i = 0; i < PropsValues.USERS_EXPORT_CSV_FIELDS.length; i++) {
103                            String field = PropsValues.USERS_EXPORT_CSV_FIELDS[i];
104    
105                            if (field.equals("fullName")) {
106                                    sb.append(CSVUtil.encode(user.getFullName()));
107                            }
108                            else if (field.startsWith("expando:")) {
109                                    String attributeName = field.substring(8);
110    
111                                    ExpandoBridge expandoBridge = user.getExpandoBridge();
112    
113                                    sb.append(
114                                            CSVUtil.encode(expandoBridge.getAttribute(attributeName)));
115                            }
116                            else {
117                                    sb.append(
118                                            CSVUtil.encode(BeanPropertiesUtil.getString(user, field)));
119                            }
120    
121                            if ((i + 1) < PropsValues.USERS_EXPORT_CSV_FIELDS.length) {
122                                    sb.append(StringPool.COMMA);
123                            }
124                    }
125    
126                    sb.append(StringPool.NEW_LINE);
127    
128                    return sb.toString();
129            }
130    
131            protected List<User> getUsers(
132                            ActionRequest actionRequest, ActionResponse actionResponse)
133                    throws Exception {
134    
135                    ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(
136                            WebKeys.THEME_DISPLAY);
137    
138                    PermissionChecker permissionChecker =
139                            themeDisplay.getPermissionChecker();
140    
141                    boolean exportAllUsers = PortalPermissionUtil.contains(
142                            permissionChecker, ActionKeys.EXPORT_USER);
143    
144                    if (!exportAllUsers &&
145                            !PortletPermissionUtil.contains(
146                                    permissionChecker, PortletKeys.USERS_ADMIN,
147                                    ActionKeys.EXPORT_USER)) {
148    
149                            return Collections.emptyList();
150                    }
151    
152                    PortletURL portletURL =
153                            ((ActionResponseImpl)actionResponse).createRenderURL(
154                                    PortletKeys.USERS_ADMIN);
155    
156                    UserSearch userSearch = new UserSearch(actionRequest, portletURL);
157    
158                    UserSearchTerms searchTerms =
159                            (UserSearchTerms)userSearch.getSearchTerms();
160    
161                    LinkedHashMap<String, Object> params =
162                            new LinkedHashMap<String, Object>();
163    
164                    long organizationId = searchTerms.getOrganizationId();
165    
166                    if (organizationId > 0) {
167                            params.put("usersOrgs", new Long(organizationId));
168                    }
169                    else if (!exportAllUsers) {
170                            User user = themeDisplay.getUser();
171    
172                            Long[] organizationIds = ArrayUtil.toArray(
173                                    user.getOrganizationIds(true));
174    
175                            if (organizationIds.length > 0) {
176                                    params.put("usersOrgs", organizationIds);
177                            }
178                    }
179    
180                    long roleId = searchTerms.getRoleId();
181    
182                    if (roleId > 0) {
183                            params.put("usersRoles", new Long(roleId));
184                    }
185    
186                    long userGroupId = searchTerms.getUserGroupId();
187    
188                    if (userGroupId > 0) {
189                            params.put("usersUserGroups", new Long(userGroupId));
190                    }
191    
192                    if (PropsValues.USERS_INDEXER_ENABLED &&
193                            PropsValues.USERS_SEARCH_WITH_INDEX) {
194    
195                            params.put("expandoAttributes", searchTerms.getKeywords());
196                    }
197    
198                    if (searchTerms.isAdvancedSearch()) {
199                            return UserLocalServiceUtil.search(
200                                    themeDisplay.getCompanyId(), searchTerms.getFirstName(),
201                                    searchTerms.getMiddleName(), searchTerms.getLastName(),
202                                    searchTerms.getScreenName(), searchTerms.getEmailAddress(),
203                                    searchTerms.getStatus(), params, searchTerms.isAndOperator(),
204                                    QueryUtil.ALL_POS, QueryUtil.ALL_POS,
205                                    (OrderByComparator<User>)null);
206                    }
207                    else {
208                            return UserLocalServiceUtil.search(
209                                    themeDisplay.getCompanyId(), searchTerms.getKeywords(),
210                                    searchTerms.getStatus(), params, QueryUtil.ALL_POS,
211                                    QueryUtil.ALL_POS, (OrderByComparator<User>)null);
212                    }
213            }
214    
215            protected String getUsersCSV(
216                            ActionRequest actionRequest, ActionResponse actionResponse)
217                    throws Exception {
218    
219                    List<User> users = getUsers(actionRequest, actionResponse);
220    
221                    if (users.isEmpty()) {
222                            return StringPool.BLANK;
223                    }
224    
225                    String exportProgressId = ParamUtil.getString(
226                            actionRequest, "exportProgressId");
227    
228                    ProgressTracker progressTracker = new ProgressTracker(exportProgressId);
229    
230                    progressTracker.start(actionRequest);
231    
232                    int percentage = 10;
233                    int total = users.size();
234    
235                    progressTracker.setPercent(percentage);
236    
237                    StringBundler sb = new StringBundler(users.size());
238    
239                    for (int i = 0; i < users.size(); i++ ) {
240                            User user = users.get(i);
241    
242                            sb.append(getUserCSV(user));
243    
244                            percentage = Math.min(10 + (i * 90) / total, 99);
245    
246                            progressTracker.setPercent(percentage);
247                    }
248    
249                    progressTracker.finish(actionRequest);
250    
251                    return sb.toString();
252            }
253    
254    }