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.file.CmsGroup;
031import org.opencms.file.CmsUser;
032import org.opencms.file.CmsUserSearchParameters;
033import org.opencms.file.CmsUserSearchParameters.SortKey;
034import org.opencms.jsp.CmsJspActionElement;
035import org.opencms.main.CmsException;
036import org.opencms.main.CmsRuntimeException;
037import org.opencms.main.OpenCms;
038import org.opencms.security.CmsPrincipal;
039import org.opencms.util.CmsRequestUtil;
040import org.opencms.util.CmsStringUtil;
041import org.opencms.util.CmsUUID;
042import org.opencms.workplace.list.A_CmsListDialog;
043import org.opencms.workplace.list.CmsHtmlList;
044import org.opencms.workplace.list.CmsListColumnAlignEnum;
045import org.opencms.workplace.list.CmsListColumnDefinition;
046import org.opencms.workplace.list.CmsListDateMacroFormatter;
047import org.opencms.workplace.list.CmsListDefaultAction;
048import org.opencms.workplace.list.CmsListDirectAction;
049import org.opencms.workplace.list.CmsListItem;
050import org.opencms.workplace.list.CmsListItemDetails;
051import org.opencms.workplace.list.CmsListItemDetailsFormatter;
052import org.opencms.workplace.list.CmsListMetadata;
053import org.opencms.workplace.list.CmsListOrderEnum;
054import org.opencms.workplace.list.CmsListSearchAction;
055import org.opencms.workplace.list.CmsListState;
056
057import java.io.IOException;
058import java.util.ArrayList;
059import java.util.Date;
060import java.util.HashSet;
061import java.util.Iterator;
062import java.util.List;
063import java.util.Set;
064
065import javax.servlet.ServletException;
066import javax.servlet.http.HttpServletRequest;
067import javax.servlet.http.HttpServletResponse;
068import javax.servlet.jsp.PageContext;
069
070import com.google.common.collect.Lists;
071
072/**
073 * Allows to select an user to transfer the permissions and attributes from list of previous selected users.<p>
074 *
075 * @since 6.0.0
076 */
077public class CmsUserTransferList extends A_CmsListDialog {
078
079    /** list action id constant. */
080    public static final String LIST_ACTION_TRANSFER = "at";
081
082    /** list column id constant. */
083    public static final String LIST_COLUMN_EMAIL = "cm";
084
085    /** list column id constant. */
086    public static final String LIST_COLUMN_LASTLOGIN = "cl";
087
088    /** list column id constant. */
089    public static final String LIST_COLUMN_LOGIN = "ci";
090
091    /** list column id constant. */
092    public static final String LIST_COLUMN_NAME = "cn";
093
094    /** list column id constant. */
095    public static final String LIST_COLUMN_TRANSFER = "ct";
096
097    /** list action id constant. */
098    public static final String LIST_DEFACTION_TRANSFER = "dt";
099
100    /** list item detail id constant. */
101    public static final String LIST_DETAIL_ADDRESS = "da";
102
103    /** list item detail id constant. */
104    public static final String LIST_DETAIL_GROUPS = "dg";
105
106    /** List id constant. */
107    public static final String LIST_ID = "lut";
108
109    /** Path to the list buttons. */
110    public static final String PATH_BUTTONS = "tools/accounts/buttons/";
111
112    /** Stores the value of the request parameter for the user id, could be a list of ids. */
113    private String m_paramUserid;
114
115    /** Stores the value of the users name, could be a list of names. */
116    private String m_userName;
117
118    /**
119     * Public constructor.<p>
120     *
121     * @param jsp an initialized JSP action element
122     */
123    public CmsUserTransferList(CmsJspActionElement jsp) {
124
125        this(LIST_ID, jsp);
126    }
127
128    /**
129     * Public constructor.<p>
130     *
131     * @param jsp an initialized JSP action element
132     * @param lazy the lazy flag
133     */
134    public CmsUserTransferList(CmsJspActionElement jsp, boolean lazy) {
135
136        this(LIST_ID, jsp, lazy);
137    }
138
139    /**
140     * Public constructor with JSP variables.<p>
141     *
142     * @param context the JSP page context
143     * @param req the JSP request
144     * @param res the JSP response
145     */
146    public CmsUserTransferList(PageContext context, HttpServletRequest req, HttpServletResponse res) {
147
148        this(new CmsJspActionElement(context, req, res));
149    }
150
151    /**
152     * Public constructor with JSP variables.<p>
153     *
154     * @param context the JSP page context
155     * @param req the JSP request
156     * @param res the JSP response
157     * @param lazy the lazy flag
158     */
159    public CmsUserTransferList(PageContext context, HttpServletRequest req, HttpServletResponse res, boolean lazy) {
160
161        this(new CmsJspActionElement(context, req, res), lazy);
162    }
163
164    /**
165     * Protected constructor.<p>
166     *
167     * @param listId the id of the specialized list
168     * @param jsp an initialized JSP action element
169     */
170    protected CmsUserTransferList(String listId, CmsJspActionElement jsp) {
171
172        super(
173            jsp,
174            listId,
175            Messages.get().container(Messages.GUI_USERS_TRANSFER_LIST_NAME_0),
176            LIST_COLUMN_NAME,
177            CmsListOrderEnum.ORDER_ASCENDING,
178            null);
179    }
180
181    /**
182     * Protected constructor.<p>
183     *
184     * @param listId the id of the specialized list
185     * @param jsp an initialized JSP action element
186     * @param lazy the lazy flag
187     */
188    protected CmsUserTransferList(String listId, CmsJspActionElement jsp, boolean lazy) {
189
190        super(
191            jsp,
192            listId,
193            Messages.get().container(Messages.GUI_USERS_TRANSFER_LIST_NAME_0),
194            LIST_COLUMN_NAME,
195            CmsListOrderEnum.ORDER_ASCENDING,
196            null,
197            lazy);
198    }
199
200    /**
201     * @see org.opencms.workplace.list.A_CmsListDialog#executeListMultiActions()
202     */
203    @Override
204    public void executeListMultiActions() throws CmsRuntimeException {
205
206        throwListUnsupportedActionException();
207    }
208
209    /**
210     * @see org.opencms.workplace.list.A_CmsListDialog#executeListSingleActions()
211     */
212    @Override
213    public void executeListSingleActions() throws IOException, ServletException {
214
215        if (getParamListAction().equals(LIST_ACTION_TRANSFER) || getParamListAction().equals(LIST_DEFACTION_TRANSFER)) {
216            // execute the delete action
217            try {
218                Iterator it = CmsStringUtil.splitAsList(getParamUserid(), CmsHtmlList.ITEM_SEPARATOR, true).iterator();
219                while (it.hasNext()) {
220                    CmsUUID id = new CmsUUID((String)it.next());
221                    getCms().deleteUser(id, new CmsUUID(getSelectedItem().getId()));
222                }
223                CmsRequestUtil.forwardRequest(getParamCloseLink(), getJsp().getRequest(), getJsp().getResponse());
224                setForwarded(true);
225            } catch (CmsException e) {
226                throw new CmsRuntimeException(
227                    Messages.get().container(Messages.ERR_TRANSFER_USER_1, getSelectedItem().get(LIST_COLUMN_NAME)),
228                    e);
229            }
230        } else {
231            throwListUnsupportedActionException();
232        }
233        listSave();
234    }
235
236    /**
237     * Returns the user id parameter value.<p>
238     *
239     * @return the user id parameter value
240     */
241    public String getParamUserid() {
242
243        return m_paramUserid;
244    }
245
246    /**
247     * Returns the users Name.<p>
248     *
249     * @return the users Name
250     */
251    public String getUserName() {
252
253        return m_userName;
254    }
255
256    /**
257     * Sets the user id parameter value.<p>
258     *
259     * @param userId the user id parameter value
260     */
261    public void setParamUserid(String userId) {
262
263        m_paramUserid = userId;
264    }
265
266    /**
267     * @see org.opencms.workplace.list.A_CmsListDialog#customHtmlStart()
268     */
269    @Override
270    protected String customHtmlStart() {
271
272        StringBuffer result = new StringBuffer(2048);
273        result.append(
274            dialogBlockStart(Messages.get().container(Messages.GUI_USERS_TRANSFER_NOTICE_0).key(getLocale())));
275        result.append("\n");
276        if (getCurrentToolPath().indexOf("/edit/") < 0) {
277            result.append(key(Messages.GUI_USER_DEPENDENCIES_SELECTED_USERS_0));
278            result.append(":<br>\n");
279            List users = CmsStringUtil.splitAsList(getUserName(), CmsHtmlList.ITEM_SEPARATOR, true);
280            result.append("<ul>\n");
281            Iterator it = users.iterator();
282            while (it.hasNext()) {
283                String name = (String)it.next();
284                result.append("<li>");
285                result.append(name);
286                result.append("</li>\n");
287            }
288            result.append("</ul>\n");
289        }
290        result.append(key(Messages.GUI_USERS_TRANSFER_NOTICE_TEXT_0));
291        result.append(dialogBlockEnd());
292        return result.toString();
293    }
294
295    /**
296     * @see org.opencms.workplace.list.A_CmsListDialog#fillDetails(java.lang.String)
297     */
298    @Override
299    protected void fillDetails(String detailId) {
300
301        // get content
302        List users = getList().getAllContent();
303        Iterator itUsers = users.iterator();
304        while (itUsers.hasNext()) {
305            CmsListItem item = (CmsListItem)itUsers.next();
306            String userName = item.get(LIST_COLUMN_LOGIN).toString();
307            StringBuffer html = new StringBuffer(512);
308            try {
309                if (detailId.equals(LIST_DETAIL_ADDRESS)) {
310                    CmsUser user = getCms().readUser(userName);
311                    // address
312                    html.append(user.getAddress());
313                    if (user.getCity() != null) {
314                        html.append("<br>");
315                        if (user.getZipcode() != null) {
316                            html.append(user.getZipcode());
317                            html.append(" ");
318                        }
319                        html.append(user.getCity());
320                    }
321                    if (user.getCountry() != null) {
322                        html.append("<br>");
323                        html.append(user.getCountry());
324                    }
325                } else if (detailId.equals(LIST_DETAIL_GROUPS)) {
326                    // groups
327                    Iterator itGroups = getCms().getGroupsOfUser(userName, false).iterator();
328                    while (itGroups.hasNext()) {
329                        String groupName = ((CmsGroup)itGroups.next()).getName();
330                        html.append(OpenCms.getWorkplaceManager().translateGroupName(groupName, true));
331                        if (itGroups.hasNext()) {
332                            html.append("<br>");
333                        }
334                        html.append("\n");
335                    }
336                } else {
337                    continue;
338                }
339            } catch (Exception e) {
340                // noop
341            }
342            item.set(detailId, html.toString());
343        }
344    }
345
346    /**
347     * @see org.opencms.workplace.list.A_CmsListDialog#getListItems()
348     */
349    @Override
350    protected List getListItems() throws CmsException {
351
352        if (!m_lazy) {
353
354            List ret = new ArrayList();
355            // get content
356            List users = getUsers();
357            Set selUsers = new HashSet(CmsStringUtil.splitAsList(getParamUserid(), CmsHtmlList.ITEM_SEPARATOR, true));
358            Iterator itUsers = users.iterator();
359            while (itUsers.hasNext()) {
360                CmsUser user = (CmsUser)itUsers.next();
361                if (selUsers.contains(user.getId().toString())) {
362                    continue;
363                }
364                CmsListItem item = getList().newItem(user.getId().toString());
365                setUserData(user, item);
366                ret.add(item);
367            }
368            return ret;
369        } else {
370
371            CmsUserSearchParameters params = getSearchParams();
372            List<CmsUser> users = OpenCms.getOrgUnitManager().searchUsers(getCms(), params);
373            int count = (int)OpenCms.getOrgUnitManager().countUsers(getCms(), params);
374            getList().setSize(count);
375            List<CmsListItem> result = Lists.newArrayList();
376            for (CmsUser user : users) {
377                CmsListItem item = getList().newItem(user.getId().toString());
378                setUserData(user, item);
379                result.add(item);
380            }
381            return result;
382
383        }
384    }
385
386    /**
387     * Returns the search parameters for lazy list paging.<p>
388     *
389     * @return the search parameters for lazy list paging
390     *
391     * @throws CmsException if something goes wrong
392     */
393    protected CmsUserSearchParameters getSearchParams() throws CmsException {
394
395        CmsListState state = getListState();
396        CmsUserSearchParameters params = new CmsUserSearchParameters();
397        String searchFilter = state.getFilter();
398        params.setSearchFilter(searchFilter);
399        params.setFilterCore(true);
400        params.setPaging(getList().getMaxItemsPerPage(), state.getPage());
401        params.setSorting(getSortKey(state.getColumn()), state.getOrder().equals(CmsListOrderEnum.ORDER_ASCENDING));
402        return params;
403    }
404
405    /**
406     * Returns the sort key for lazy list paging.<p>
407     *
408     * @param column the current column
409     * @return the sort key to use
410     */
411    protected SortKey getSortKey(String column) {
412
413        if (column == null) {
414            return null;
415        }
416        if (column.equals(LIST_COLUMN_EMAIL)) {
417            return SortKey.email;
418        } else if (column.equals(LIST_COLUMN_LOGIN)) {
419            return SortKey.loginName;
420        } else if (column.equals(LIST_COLUMN_NAME)) {
421            return SortKey.fullName;
422        }
423        return null;
424    }
425
426    /**
427     * Returns the list of users to display.<p>
428     *
429     * @return the list of users to display
430     *
431     * @throws CmsException if something goes wrong
432     */
433    protected List<CmsUser> getUsers() throws CmsException {
434
435        return CmsPrincipal.filterCoreUsers(OpenCms.getOrgUnitManager().getUsers(getCms(), "", true));
436    }
437
438    /**
439     * @see org.opencms.workplace.CmsWorkplace#initMessages()
440     */
441    @Override
442    protected void initMessages() {
443
444        // add specific dialog resource bundle
445        addMessages(Messages.get().getBundleName());
446        // add default resource bundles
447        super.initMessages();
448    }
449
450    /**
451     * @see org.opencms.workplace.list.A_CmsListDialog#setColumns(org.opencms.workplace.list.CmsListMetadata)
452     */
453    @Override
454    protected void setColumns(CmsListMetadata metadata) {
455
456        if (m_lazy) {
457            metadata.setSelfManaged(true);
458        }
459        // create column for transfer
460        CmsListColumnDefinition transferCol = new CmsListColumnDefinition(LIST_COLUMN_TRANSFER);
461        transferCol.setName(Messages.get().container(Messages.GUI_USERS_TRANSFER_LIST_COLS_TRANSFER_0));
462        transferCol.setHelpText(Messages.get().container(Messages.GUI_USERS_TRANSFER_LIST_COLS_TRANSFER_HELP_0));
463        transferCol.setWidth("20");
464        transferCol.setAlign(CmsListColumnAlignEnum.ALIGN_CENTER);
465        transferCol.setSorteable(false);
466
467        // add transfer action
468        setTransferAction(transferCol);
469
470        // add it to the list definition
471        metadata.addColumn(transferCol);
472
473        // create column for login
474        CmsListColumnDefinition loginCol = new CmsListColumnDefinition(LIST_COLUMN_LOGIN);
475        loginCol.setName(Messages.get().container(Messages.GUI_USERS_LIST_COLS_LOGIN_0));
476        loginCol.setWidth("20%");
477
478        // create default transfer action
479        CmsListDefaultAction defTransferAction = new CmsListDefaultAction(LIST_DEFACTION_TRANSFER);
480        defTransferAction.setName(Messages.get().container(Messages.GUI_USERS_TRANSFER_LIST_DEFACTION_TRANSFER_NAME_0));
481        defTransferAction.setHelpText(
482            Messages.get().container(Messages.GUI_USERS_TRANSFER_LIST_DEFACTION_TRANSFER_HELP_0));
483        loginCol.addDefaultAction(defTransferAction);
484
485        // add it to the list definition
486        metadata.addColumn(loginCol);
487
488        // add column for name
489        CmsListColumnDefinition nameCol = new CmsListColumnDefinition(LIST_COLUMN_NAME);
490        nameCol.setName(Messages.get().container(Messages.GUI_USERS_LIST_COLS_USERNAME_0));
491        nameCol.setWidth("30%");
492        metadata.addColumn(nameCol);
493
494        // add column for email
495        CmsListColumnDefinition emailCol = new CmsListColumnDefinition(LIST_COLUMN_EMAIL);
496        emailCol.setName(Messages.get().container(Messages.GUI_USERS_LIST_COLS_EMAIL_0));
497        emailCol.setWidth("30%");
498        metadata.addColumn(emailCol);
499
500        // add column for last login date
501        CmsListColumnDefinition lastLoginCol = new CmsListColumnDefinition(LIST_COLUMN_LASTLOGIN);
502        lastLoginCol.setName(Messages.get().container(Messages.GUI_USERS_LIST_COLS_LASTLOGIN_0));
503        lastLoginCol.setWidth("20%");
504        lastLoginCol.setFormatter(CmsListDateMacroFormatter.getDefaultDateFormatter());
505        metadata.addColumn(lastLoginCol);
506    }
507
508    /**
509     * @see org.opencms.workplace.list.A_CmsListDialog#setIndependentActions(org.opencms.workplace.list.CmsListMetadata)
510     */
511    @Override
512    protected void setIndependentActions(CmsListMetadata metadata) {
513
514        // add user address details
515        CmsListItemDetails userAddressDetails = new CmsListItemDetails(LIST_DETAIL_ADDRESS);
516        userAddressDetails.setAtColumn(LIST_COLUMN_LOGIN);
517        userAddressDetails.setVisible(false);
518        userAddressDetails.setShowActionName(Messages.get().container(Messages.GUI_USERS_DETAIL_SHOW_ADDRESS_NAME_0));
519        userAddressDetails.setShowActionHelpText(
520            Messages.get().container(Messages.GUI_USERS_DETAIL_SHOW_ADDRESS_HELP_0));
521        userAddressDetails.setHideActionName(Messages.get().container(Messages.GUI_USERS_DETAIL_HIDE_ADDRESS_NAME_0));
522        userAddressDetails.setHideActionHelpText(
523            Messages.get().container(Messages.GUI_USERS_DETAIL_HIDE_ADDRESS_HELP_0));
524        userAddressDetails.setName(Messages.get().container(Messages.GUI_USERS_DETAIL_ADDRESS_NAME_0));
525        userAddressDetails.setFormatter(
526            new CmsListItemDetailsFormatter(Messages.get().container(Messages.GUI_USERS_DETAIL_ADDRESS_NAME_0)));
527        metadata.addItemDetails(userAddressDetails);
528
529        // add user groups details
530        CmsListItemDetails userGroupsDetails = new CmsListItemDetails(LIST_DETAIL_GROUPS);
531        userGroupsDetails.setAtColumn(LIST_COLUMN_LOGIN);
532        userGroupsDetails.setVisible(false);
533        userGroupsDetails.setShowActionName(Messages.get().container(Messages.GUI_USERS_DETAIL_SHOW_GROUPS_NAME_0));
534        userGroupsDetails.setShowActionHelpText(Messages.get().container(Messages.GUI_USERS_DETAIL_SHOW_GROUPS_HELP_0));
535        userGroupsDetails.setHideActionName(Messages.get().container(Messages.GUI_USERS_DETAIL_HIDE_GROUPS_NAME_0));
536        userGroupsDetails.setHideActionHelpText(Messages.get().container(Messages.GUI_USERS_DETAIL_HIDE_GROUPS_HELP_0));
537        userGroupsDetails.setName(Messages.get().container(Messages.GUI_USERS_DETAIL_GROUPS_NAME_0));
538        userGroupsDetails.setFormatter(
539            new CmsListItemDetailsFormatter(Messages.get().container(Messages.GUI_USERS_DETAIL_GROUPS_NAME_0)));
540        metadata.addItemDetails(userGroupsDetails);
541
542        // makes the list searchable
543        CmsListSearchAction searchAction = new CmsListSearchAction(metadata.getColumnDefinition(LIST_COLUMN_LOGIN));
544        searchAction.addColumn(metadata.getColumnDefinition(LIST_COLUMN_NAME));
545        metadata.setSearchAction(searchAction);
546    }
547
548    /**
549     * @see org.opencms.workplace.list.A_CmsListDialog#setMultiActions(org.opencms.workplace.list.CmsListMetadata)
550     */
551    @Override
552    protected void setMultiActions(CmsListMetadata metadata) {
553
554        // no-op
555    }
556
557    /**
558     * Sets the icon actions for the transfer list.<p>
559     *
560     * @param transferCol the column to set the action
561     */
562    protected void setTransferAction(CmsListColumnDefinition transferCol) {
563
564        CmsListDirectAction transferAction = new CmsListDirectAction(LIST_ACTION_TRANSFER);
565        transferAction.setName(Messages.get().container(Messages.GUI_USERS_TRANSFER_LIST_ACTION_TRANSFER_NAME_0));
566        transferAction.setHelpText(Messages.get().container(Messages.GUI_USERS_TRANSFER_LIST_ACTION_TRANSFER_HELP_0));
567        transferAction.setIconPath(PATH_BUTTONS + "user.png");
568        transferCol.addDirectAction(transferAction);
569    }
570
571    /**
572     * Sets all needed data of the user into the list item object.<p>
573     *
574     * @param user the user to set the data for
575     * @param item the list item object to set the data into
576     */
577    protected void setUserData(CmsUser user, CmsListItem item) {
578
579        item.set(LIST_COLUMN_LOGIN, user.getName());
580        item.set(LIST_COLUMN_NAME, user.getFullName());
581        item.set(LIST_COLUMN_EMAIL, user.getEmail());
582        item.set(LIST_COLUMN_LASTLOGIN, new Date(user.getLastlogin()));
583    }
584
585    /**
586     * @see org.opencms.workplace.list.A_CmsListDialog#validateParamaters()
587     */
588    @Override
589    protected void validateParamaters() throws Exception {
590
591        m_userName = "";
592        Iterator itUsers = CmsStringUtil.splitAsList(getParamUserid(), CmsHtmlList.ITEM_SEPARATOR, true).iterator();
593        while (itUsers.hasNext()) {
594            CmsUUID id = new CmsUUID(itUsers.next().toString());
595            m_userName += getCms().readUser(id).getName();
596            if (itUsers.hasNext()) {
597                m_userName += CmsHtmlList.ITEM_SEPARATOR;
598            }
599        }
600    }
601
602}