001    /**
002     * Copyright (c) 2000-2012 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portal.kernel.webdav;
016    
017    import com.liferay.portal.NoSuchGroupException;
018    import com.liferay.portal.NoSuchUserException;
019    import com.liferay.portal.kernel.dao.orm.QueryUtil;
020    import com.liferay.portal.kernel.log.Log;
021    import com.liferay.portal.kernel.log.LogFactoryUtil;
022    import com.liferay.portal.kernel.security.pacl.permission.PortalRuntimePermission;
023    import com.liferay.portal.kernel.util.CharPool;
024    import com.liferay.portal.kernel.util.GetterUtil;
025    import com.liferay.portal.kernel.util.HttpUtil;
026    import com.liferay.portal.kernel.util.OrderByComparator;
027    import com.liferay.portal.kernel.util.StringPool;
028    import com.liferay.portal.kernel.util.StringUtil;
029    import com.liferay.portal.kernel.util.Time;
030    import com.liferay.portal.kernel.util.UniqueList;
031    import com.liferay.portal.kernel.util.Validator;
032    import com.liferay.portal.kernel.xml.Namespace;
033    import com.liferay.portal.kernel.xml.SAXReaderUtil;
034    import com.liferay.portal.model.Group;
035    import com.liferay.portal.model.GroupConstants;
036    import com.liferay.portal.model.User;
037    import com.liferay.portal.service.GroupLocalServiceUtil;
038    import com.liferay.portal.service.UserLocalServiceUtil;
039    import com.liferay.portal.util.comparator.GroupFriendlyURLComparator;
040    
041    import java.util.ArrayList;
042    import java.util.Collection;
043    import java.util.Collections;
044    import java.util.LinkedHashMap;
045    import java.util.List;
046    import java.util.Map;
047    import java.util.TreeMap;
048    
049    import javax.servlet.http.HttpServletRequest;
050    
051    /**
052     * @author Brian Wing Shun Chan
053     * @author Alexander Chow
054     * @author Raymond Augé
055     */
056    public class WebDAVUtil {
057    
058            public static final Namespace DAV_URI = SAXReaderUtil.createNamespace(
059                    "D", "DAV:");
060    
061            public static final int SC_LOCKED = 423;
062    
063            public static final int SC_MULTI_STATUS = 207;
064    
065            public static final String TOKEN_PREFIX = "opaquelocktoken:";
066    
067            public static void addStorage(WebDAVStorage storage) {
068                    getInstance()._addStorage(storage);
069            }
070    
071            public static Namespace createNamespace(String prefix, String uri) {
072                    Namespace namespace = null;
073    
074                    if (uri.equals(WebDAVUtil.DAV_URI.getURI())) {
075                            namespace = WebDAVUtil.DAV_URI;
076                    }
077                    else if (Validator.isNull(prefix)) {
078                            namespace = SAXReaderUtil.createNamespace(uri);
079                    }
080                    else {
081                            namespace = SAXReaderUtil.createNamespace(prefix, uri);
082                    }
083    
084                    return namespace;
085            }
086    
087            public static void deleteStorage(WebDAVStorage storage) {
088                    getInstance()._deleteStorage(storage);
089            }
090    
091            public static long getDepth(HttpServletRequest request) {
092                    String value = GetterUtil.getString(request.getHeader("Depth"));
093    
094                    if (_log.isDebugEnabled()) {
095                            _log.debug("\"Depth\" header is " + value);
096                    }
097    
098                    if (value.equals("0")) {
099                            return 0;
100                    }
101                    else {
102                            return -1;
103                    }
104            }
105    
106            public static String getDestination(
107                    HttpServletRequest request, String rootPath) {
108    
109                    String headerDestination = request.getHeader("Destination");
110                    String[] pathSegments = StringUtil.split(headerDestination, rootPath);
111    
112                    String destination = pathSegments[pathSegments.length - 1];
113    
114                    destination = HttpUtil.decodePath(destination);
115    
116                    if (_log.isDebugEnabled()) {
117                            _log.debug("Destination " + destination);
118                    }
119    
120                    return destination;
121            }
122    
123            public static long getGroupId(long companyId, String path)
124                    throws WebDAVException {
125    
126                    String[] pathArray = getPathArray(path);
127    
128                    return getGroupId(companyId, pathArray);
129            }
130    
131            public static long getGroupId(long companyId, String[] pathArray)
132                    throws WebDAVException {
133    
134                    try {
135                            if (pathArray.length == 0) {
136                                    return 0;
137                            }
138    
139                            String name = pathArray[0];
140    
141                            try {
142                                    Group group = GroupLocalServiceUtil.getFriendlyURLGroup(
143                                            companyId, StringPool.SLASH + name);
144    
145                                    return group.getGroupId();
146                            }
147                            catch (NoSuchGroupException nsge) {
148                            }
149    
150                            try {
151                                    User user = UserLocalServiceUtil.getUserByScreenName(
152                                            companyId, name);
153    
154                                    Group group = user.getGroup();
155    
156                                    return group.getGroupId();
157                            }
158                            catch (NoSuchUserException nsue) {
159                            }
160                    }
161                    catch (Exception e) {
162                            throw new WebDAVException(e);
163                    }
164    
165                    return 0;
166            }
167    
168            public static List<Group> getGroups(long userId) throws Exception {
169                    User user = UserLocalServiceUtil.getUser(userId);
170    
171                    return getGroups(user);
172            }
173    
174            public static List<Group> getGroups(User user) throws Exception {
175    
176                    // Guest
177    
178                    if (user.isDefaultUser()) {
179                            List<Group> groups = new ArrayList<Group>();
180    
181                            Group group = GroupLocalServiceUtil.getGroup(
182                                    user.getCompanyId(), GroupConstants.GUEST);
183    
184                            groups.add(group);
185    
186                            return groups;
187                    }
188    
189                    // Communities
190    
191                    List<Group> groups = new UniqueList<Group>();
192    
193                    LinkedHashMap<String, Object> params =
194                            new LinkedHashMap<String, Object>();
195    
196                    params.put("usersGroups", user.getUserId());
197    
198                    OrderByComparator orderByComparator = new GroupFriendlyURLComparator(
199                            true);
200    
201                    groups.addAll(
202                            GroupLocalServiceUtil.search(
203                                    user.getCompanyId(), null, null, params, QueryUtil.ALL_POS,
204                                    QueryUtil.ALL_POS, orderByComparator));
205    
206                    // Organizations
207    
208                    groups.addAll(
209                            GroupLocalServiceUtil.getUserOrganizationsGroups(
210                                    user.getUserId(), QueryUtil.ALL_POS, QueryUtil.ALL_POS));
211    
212                    // User
213    
214                    if (!user.isDefaultUser()) {
215                            groups.add(user.getGroup());
216                    }
217    
218                    Collections.sort(groups, orderByComparator);
219    
220                    return groups;
221            }
222    
223            public static WebDAVUtil getInstance() {
224                    PortalRuntimePermission.checkGetBeanProperty(WebDAVUtil.class);
225    
226                    return _instance;
227            }
228    
229            public static String getLockUuid(HttpServletRequest request)
230                    throws WebDAVException {
231    
232                    String token = StringPool.BLANK;
233    
234                    String value = GetterUtil.getString(request.getHeader("If"));
235    
236                    if (_log.isDebugEnabled()) {
237                            _log.debug("\"If\" header is " + value);
238                    }
239    
240                    if (value.contains("(<DAV:no-lock>)")) {
241                            if (_log.isWarnEnabled()) {
242                                    _log.warn("Lock tokens can never be <DAV:no-lock>");
243                            }
244    
245                            throw new WebDAVException();
246                    }
247    
248                    int beg = value.indexOf(TOKEN_PREFIX);
249    
250                    if (beg >= 0) {
251                            beg += TOKEN_PREFIX.length();
252    
253                            if (beg < value.length()) {
254                                    int end = value.indexOf(CharPool.GREATER_THAN, beg);
255    
256                                    token = GetterUtil.getString(value.substring(beg, end));
257                            }
258                    }
259    
260                    return token;
261            }
262    
263            public static String[] getPathArray(String path) {
264                    return getPathArray(path, false);
265            }
266    
267            public static String[] getPathArray(String path, boolean fixTrailing) {
268                    path = HttpUtil.fixPath(path, true, fixTrailing);
269    
270                    return StringUtil.split(path, CharPool.SLASH);
271            }
272    
273            public static String getResourceName(String[] pathArray) {
274                    if (pathArray.length <= 2) {
275                            return StringPool.BLANK;
276                    }
277                    else {
278                            return pathArray[pathArray.length - 1];
279                    }
280            }
281    
282            public static WebDAVStorage getStorage(String token) {
283                    return getInstance()._getStorage(token);
284            }
285    
286            public static Collection<String> getStorageTokens() {
287                    return getInstance()._getStorageTokens();
288            }
289    
290            public static long getTimeout(HttpServletRequest request) {
291                    final String TIME_PREFIX = "Second-";
292    
293                    long timeout = 0;
294    
295                    String value = GetterUtil.getString(request.getHeader("Timeout"));
296    
297                    if (_log.isDebugEnabled()) {
298                            _log.debug("\"Timeout\" header is " + value);
299                    }
300    
301                    int index = value.indexOf(TIME_PREFIX);
302    
303                    if (index >= 0) {
304                            index += TIME_PREFIX.length();
305    
306                            if (index < value.length()) {
307                                    timeout = GetterUtil.getLong(value.substring(index));
308                            }
309                    }
310    
311                    return timeout * Time.SECOND;
312            }
313    
314            public static boolean isOverwrite(HttpServletRequest request) {
315                    return getInstance()._isOverwrite(request);
316            }
317    
318            private WebDAVUtil() {
319                    _storageMap = new TreeMap<String, WebDAVStorage>();
320            }
321    
322            private void _addStorage(WebDAVStorage storage) {
323                    _storageMap.put(storage.getToken(), storage);
324            }
325    
326            private void _deleteStorage(WebDAVStorage storage) {
327                    if (storage != null) {
328                            _storageMap.remove(storage.getToken());
329                    }
330            }
331    
332            private WebDAVStorage _getStorage(String token) {
333                    return _storageMap.get(token);
334            }
335    
336            private Collection<String> _getStorageTokens() {
337                    return _storageMap.keySet();
338            }
339    
340            private boolean _isOverwrite(HttpServletRequest request) {
341                    String value = GetterUtil.getString(request.getHeader("Overwrite"));
342    
343                    if (value.equalsIgnoreCase("F") || !GetterUtil.getBoolean(value)) {
344                            return false;
345                    }
346                    else {
347                            return true;
348                    }
349            }
350    
351            private static Log _log = LogFactoryUtil.getLog(WebDAVUtil.class);
352    
353            private static WebDAVUtil _instance = new WebDAVUtil();
354    
355            private Map<String, WebDAVStorage> _storageMap;
356    
357    }