001/*
002 * This library is part of OpenCms -
003 * the Open Source Content Management System
004 *
005 * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com)
006 *
007 * This library is free software; you can redistribute it and/or
008 * modify it under the terms of the GNU Lesser General Public
009 * License as published by the Free Software Foundation; either
010 * version 2.1 of the License, or (at your option) any later version.
011 *
012 * This library is distributed in the hope that it will be useful,
013 * but WITHOUT ANY WARRANTY; without even the implied warranty of
014 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
015 * Lesser General Public License for more details.
016 *
017 * For further information about Alkacon Software GmbH & Co. KG, please see the
018 * company website: http://www.alkacon.com
019 *
020 * For further information about OpenCms, please see the
021 * project website: http://www.opencms.org
022 *
023 * You should have received a copy of the GNU Lesser General Public
024 * License along with this library; if not, write to the Free Software
025 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
026 */
027
028package org.opencms.workplace.tools.accounts;
029
030import org.opencms.db.CmsUserExportSettings;
031import org.opencms.file.CmsUser;
032import org.opencms.flex.CmsFlexController;
033import org.opencms.jsp.CmsJspActionElement;
034import org.opencms.main.CmsException;
035import org.opencms.main.CmsRuntimeException;
036import org.opencms.main.OpenCms;
037import org.opencms.security.CmsRole;
038import org.opencms.security.I_CmsPrincipal;
039import org.opencms.ui.apps.user.CmsImportExportUserDialog;
040import org.opencms.util.CmsRequestUtil;
041import org.opencms.util.CmsStringUtil;
042import org.opencms.util.CmsUUID;
043
044import java.lang.reflect.InvocationTargetException;
045import java.lang.reflect.Method;
046import java.util.HashMap;
047import java.util.Iterator;
048import java.util.List;
049import java.util.Map;
050import java.util.Random;
051
052import javax.servlet.http.HttpServletRequest;
053import javax.servlet.http.HttpServletResponse;
054import javax.servlet.jsp.PageContext;
055
056/**
057 * Generates a CSV file for a given list.<p>
058 *
059 * @since 6.0.0
060 */
061public class CmsUsersCsvDownloadDialog extends A_CmsUserDataImexportDialog {
062
063    /**
064     * Public constructor.<p>
065     *
066     * @param jsp an initialized JSP action element
067     */
068    public CmsUsersCsvDownloadDialog(CmsJspActionElement jsp) {
069
070        super(jsp);
071    }
072
073    /**
074     * Public constructor with JSP variables.<p>
075     *
076     * @param context the JSP page context
077     * @param req the JSP request
078     * @param res the JSP response
079     */
080    public CmsUsersCsvDownloadDialog(PageContext context, HttpServletRequest req, HttpServletResponse res) {
081
082        this(new CmsJspActionElement(context, req, res));
083    }
084
085    /**
086     * @see org.opencms.workplace.tools.accounts.A_CmsUserDataImexportDialog#actionCommit()
087     */
088    @Override
089    public void actionCommit() {
090
091        // empty
092    }
093
094    /**
095     * @see org.opencms.workplace.CmsWidgetDialog#dialogButtonsCustom()
096     */
097    @Override
098    public String dialogButtonsCustom() {
099
100        return dialogButtons(new int[] {BUTTON_CLOSE}, new String[1]);
101    }
102
103    /**
104     * Generates the CSV file for the given users.<p>
105     *
106     * @return CSV file
107     */
108    public String generateCsv() {
109
110        Map<String, List<String>> objects = getData();
111
112        // get the data object from session
113        List<String> groups = objects.get("groups");
114        List<String> roles = objects.get("roles");
115
116        Map<CmsUUID, CmsUser> exportUsers = new HashMap<CmsUUID, CmsUser>();
117        try {
118            if (((groups == null) || (groups.size() < 1)) && ((roles == null) || (roles.size() < 1))) {
119                exportUsers = CmsImportExportUserDialog.addExportAllUsers(getCms(), getParamOufqn(), exportUsers);
120            } else {
121                exportUsers = CmsImportExportUserDialog.addExportUsersFromGroups(getCms(), groups, exportUsers);
122                exportUsers = CmsImportExportUserDialog.addExportUsersFromRoles(
123                    getCms(),
124                    getParamOufqn(),
125                    roles,
126                    exportUsers);
127            }
128        } catch (CmsException e) {
129            throw new CmsRuntimeException(Messages.get().container(Messages.ERR_GET_EXPORT_USERS_0), e);
130        }
131
132        StringBuffer buffer = new StringBuffer();
133        CmsUserExportSettings settings = OpenCms.getImportExportManager().getUserExportSettings();
134
135        String separator = CmsStringUtil.substitute(settings.getSeparator(), "\\t", "\t");
136        List<String> values = settings.getColumns();
137
138        buffer.append("name");
139        Iterator<String> itValues = values.iterator();
140        while (itValues.hasNext()) {
141            buffer.append(separator);
142            buffer.append(itValues.next());
143        }
144        buffer.append("\n");
145
146        Object[] users = exportUsers.values().toArray();
147
148        for (int i = 0; i < users.length; i++) {
149            CmsUser exportUser = (CmsUser)users[i];
150            if (!exportUser.getOuFqn().equals(getParamOufqn())) {
151                // skip users of others ous
152                continue;
153            }
154            if (!isExportable(exportUser)) {
155                continue;
156            }
157            buffer.append(exportUser.getSimpleName());
158            itValues = values.iterator();
159            while (itValues.hasNext()) {
160                buffer.append(separator);
161                String curValue = itValues.next();
162                try {
163                    Method method = CmsUser.class.getMethod(
164                        "get" + curValue.substring(0, 1).toUpperCase() + curValue.substring(1));
165                    String curOutput = (String)method.invoke(exportUser);
166                    if (CmsStringUtil.isEmptyOrWhitespaceOnly(curOutput) || curOutput.equals("null")) {
167                        curOutput = (String)exportUser.getAdditionalInfo(curValue);
168                    }
169
170                    if (curValue.equals("password")) {
171                        curOutput = OpenCms.getPasswordHandler().getDigestType() + "_" + curOutput;
172                    }
173
174                    if (!CmsStringUtil.isEmptyOrWhitespaceOnly(curOutput) && !curOutput.equals("null")) {
175                        buffer.append(curOutput);
176                    }
177                } catch (NoSuchMethodException e) {
178                    Object obj = exportUser.getAdditionalInfo(curValue);
179                    if (obj != null) {
180                        String curOutput = String.valueOf(obj);
181                        if (CmsStringUtil.isNotEmptyOrWhitespaceOnly(curOutput)) {
182                            buffer.append(curOutput);
183                        }
184                    }
185                } catch (IllegalAccessException e) {
186                    throw new CmsRuntimeException(Messages.get().container(Messages.ERR_ILLEGAL_ACCESS_0), e);
187                } catch (InvocationTargetException e) {
188                    throw new CmsRuntimeException(Messages.get().container(Messages.ERR_INVOCATION_TARGET_0), e);
189                }
190            }
191            buffer.append("\n");
192        }
193        HttpServletResponse res = CmsFlexController.getController(getJsp().getRequest()).getTopResponse();
194        res.setContentType("text/comma-separated-values");
195        String filename = "export_users" + new Random().nextInt(1024) + ".csv";
196        res.setHeader(
197            "Content-Disposition",
198            new StringBuffer("attachment; filename=\"").append(filename).append("\"").toString());
199        return buffer.toString();
200    }
201
202    /**
203     * Creates the dialog HTML for all defined widgets of the named dialog (page).<p>
204     *
205     * This overwrites the method from the super class to create a layout variation for the widgets.<p>
206     *
207     * @param dialog the dialog (page) to get the HTML for
208     * @return the dialog HTML for all defined widgets of the named dialog (page)
209     */
210    @Override
211    protected String createDialogHtml(String dialog) {
212
213        StringBuffer result = new StringBuffer(1024);
214
215        result.append(createWidgetTableStart());
216        // show error header once if there were validation errors
217        result.append(createWidgetErrorHeader());
218
219        if (dialog.equals(PAGES[0])) {
220            // create the widgets for the first dialog page
221            result.append("<script >\n");
222            result.append("function download(){\n");
223            result.append("\twindow.open(\"").append(
224                getJsp().link(
225                    CmsRequestUtil.appendParameter(
226                        getDownloadPath(),
227                        A_CmsOrgUnitDialog.PARAM_OUFQN,
228                        getParamOufqn()))).append("\", \"usecvs\");\n");
229            result.append("}\n");
230            result.append("window.setTimeout(\"download()\",500);\n");
231            result.append("</script>\n");
232            result.append(dialogBlockStart(key(Messages.GUI_USERDATA_EXPORT_LABEL_HINT_BLOCK_0)));
233            result.append(key(Messages.GUI_USERDATA_DOWNLOAD_LABEL_HINT_TEXT_0));
234            result.append(" <a href='javascript:download()'>");
235            result.append(key(Messages.GUI_USERDATA_DOWNLOAD_LABEL_HINT_CLICK_0));
236            result.append("</a>.");
237            result.append(dialogBlockEnd());
238        }
239
240        result.append(createWidgetTableEnd());
241        return result.toString();
242    }
243
244    /**
245     * @see org.opencms.workplace.tools.accounts.A_CmsUserDataImexportDialog#defineWidgets()
246     */
247    @Override
248    protected void defineWidgets() {
249
250        // empty
251    }
252
253    /**
254     * Returns the export options data.<p>
255     *
256     * @return the export options data
257     */
258    protected Map<String, List<String>> getData() {
259
260        return (Map<String, List<String>>)((Map<String, Object>)getSettings().getDialogObject()).get(
261            CmsUserDataExportDialog.class.getName());
262    }
263
264    /**
265     * Returns the download path.<p>
266     *
267     * @return the download path
268     */
269    protected String getDownloadPath() {
270
271        return "/system/workplace/admin/accounts/imexport_user_data/csvdownload.jsp";
272    }
273
274    /**
275     * Checks if the user can be exported.<p>
276     *
277     * @param exportUser the suer to check
278     *
279     * @return <code>true</code> if the user can be exported
280     */
281    protected boolean isExportable(CmsUser exportUser) {
282
283        return exportUser.getFlags() < I_CmsPrincipal.FLAG_CORE_LIMIT;
284    }
285
286    /**
287     * @see org.opencms.workplace.CmsWidgetDialog#validateParamaters()
288     */
289    @Override
290    protected void validateParamaters() throws Exception {
291
292        if (getParamOufqn() == null) {
293            setParamOufqn("");
294        }
295        OpenCms.getRoleManager().checkRole(getCms(), CmsRole.ACCOUNT_MANAGER.forOrgUnit(getParamOufqn()));
296    }
297}