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.portal.kernel.webdav;
016    
017    import com.liferay.portal.kernel.dao.orm.QueryUtil;
018    import com.liferay.portal.kernel.log.Log;
019    import com.liferay.portal.kernel.log.LogFactoryUtil;
020    import com.liferay.portal.kernel.security.pacl.permission.PortalRuntimePermission;
021    import com.liferay.portal.kernel.util.CharPool;
022    import com.liferay.portal.kernel.util.FileUtil;
023    import com.liferay.portal.kernel.util.GetterUtil;
024    import com.liferay.portal.kernel.util.HttpUtil;
025    import com.liferay.portal.kernel.util.OrderByComparator;
026    import com.liferay.portal.kernel.util.StringPool;
027    import com.liferay.portal.kernel.util.StringUtil;
028    import com.liferay.portal.kernel.util.Time;
029    import com.liferay.portal.kernel.util.Validator;
030    import com.liferay.portal.kernel.xml.Namespace;
031    import com.liferay.portal.kernel.xml.SAXReaderUtil;
032    import com.liferay.portal.model.Group;
033    import com.liferay.portal.model.GroupConstants;
034    import com.liferay.portal.model.User;
035    import com.liferay.portal.service.GroupLocalServiceUtil;
036    import com.liferay.portal.service.UserLocalServiceUtil;
037    import com.liferay.portal.util.comparator.GroupFriendlyURLComparator;
038    import com.liferay.portlet.documentlibrary.util.DL;
039    import com.liferay.registry.Registry;
040    import com.liferay.registry.RegistryUtil;
041    import com.liferay.registry.ServiceReference;
042    import com.liferay.registry.ServiceRegistration;
043    import com.liferay.registry.ServiceTracker;
044    import com.liferay.registry.ServiceTrackerCustomizer;
045    import com.liferay.registry.collections.ServiceRegistrationMap;
046    
047    import java.util.ArrayList;
048    import java.util.Collection;
049    import java.util.Collections;
050    import java.util.HashSet;
051    import java.util.LinkedHashMap;
052    import java.util.List;
053    import java.util.Map;
054    import java.util.Set;
055    import java.util.concurrent.ConcurrentSkipListMap;
056    
057    import javax.servlet.http.HttpServletRequest;
058    
059    /**
060     * @author Brian Wing Shun Chan
061     * @author Alexander Chow
062     * @author Raymond Aug??
063     */
064    public class WebDAVUtil {
065    
066            public static final Namespace DAV_URI = SAXReaderUtil.createNamespace(
067                    "D", "DAV:");
068    
069            public static final int SC_LOCKED = 423;
070    
071            public static final int SC_MULTI_STATUS = 207;
072    
073            public static final String TOKEN_PREFIX = "opaquelocktoken:";
074    
075            public static void addStorage(WebDAVStorage storage) {
076                    getInstance()._addStorage(storage);
077            }
078    
079            public static Namespace createNamespace(String prefix, String uri) {
080                    Namespace namespace = null;
081    
082                    if (uri.equals(WebDAVUtil.DAV_URI.getURI())) {
083                            namespace = WebDAVUtil.DAV_URI;
084                    }
085                    else if (Validator.isNull(prefix)) {
086                            namespace = SAXReaderUtil.createNamespace(uri);
087                    }
088                    else {
089                            namespace = SAXReaderUtil.createNamespace(prefix, uri);
090                    }
091    
092                    return namespace;
093            }
094    
095            public static void deleteStorage(WebDAVStorage storage) {
096                    getInstance()._deleteStorage(storage);
097            }
098    
099            public static long getDepth(HttpServletRequest request) {
100                    String value = GetterUtil.getString(request.getHeader("Depth"));
101    
102                    if (_log.isDebugEnabled()) {
103                            _log.debug("\"Depth\" header is " + value);
104                    }
105    
106                    if (value.equals("0")) {
107                            return 0;
108                    }
109                    else {
110                            return -1;
111                    }
112            }
113    
114            public static String getDestination(
115                    HttpServletRequest request, String rootPath) {
116    
117                    String headerDestination = request.getHeader("Destination");
118                    String[] pathSegments = StringUtil.split(headerDestination, rootPath);
119    
120                    String destination = pathSegments[pathSegments.length - 1];
121    
122                    destination = HttpUtil.decodePath(destination);
123    
124                    if (_log.isDebugEnabled()) {
125                            _log.debug("Destination " + destination);
126                    }
127    
128                    return destination;
129            }
130    
131            public static long getGroupId(long companyId, String path)
132                    throws WebDAVException {
133    
134                    String[] pathArray = getPathArray(path);
135    
136                    return getGroupId(companyId, pathArray);
137            }
138    
139            public static long getGroupId(long companyId, String[] pathArray)
140                    throws WebDAVException {
141    
142                    try {
143                            if (pathArray.length == 0) {
144                                    return 0;
145                            }
146    
147                            String name = pathArray[0];
148    
149                            Group group = GroupLocalServiceUtil.fetchFriendlyURLGroup(
150                                    companyId, StringPool.SLASH + name);
151    
152                            if (group != null) {
153                                    return group.getGroupId();
154                            }
155    
156                            User user = UserLocalServiceUtil.fetchUserByScreenName(
157                                    companyId, name);
158    
159                            if (user != null) {
160                                    group = user.getGroup();
161    
162                                    return group.getGroupId();
163                            }
164                    }
165                    catch (Exception e) {
166                            throw new WebDAVException(e);
167                    }
168    
169                    return 0;
170            }
171    
172            public static List<Group> getGroups(long userId) throws Exception {
173                    User user = UserLocalServiceUtil.getUser(userId);
174    
175                    return getGroups(user);
176            }
177    
178            public static List<Group> getGroups(User user) throws Exception {
179    
180                    // Guest
181    
182                    if (user.isDefaultUser()) {
183                            List<Group> groups = new ArrayList<>();
184    
185                            Group group = GroupLocalServiceUtil.getGroup(
186                                    user.getCompanyId(), GroupConstants.GUEST);
187    
188                            groups.add(group);
189    
190                            return groups;
191                    }
192    
193                    // Communities
194    
195                    Set<Group> groups = new HashSet<>();
196    
197                    LinkedHashMap<String, Object> params = new LinkedHashMap<>();
198    
199                    params.put("usersGroups", user.getUserId());
200    
201                    OrderByComparator<Group> orderByComparator =
202                            new GroupFriendlyURLComparator(true);
203    
204                    groups.addAll(
205                            GroupLocalServiceUtil.search(
206                                    user.getCompanyId(), null, null, params, QueryUtil.ALL_POS,
207                                    QueryUtil.ALL_POS, orderByComparator));
208    
209                    // Organizations
210    
211                    groups.addAll(
212                            GroupLocalServiceUtil.getUserOrganizationsGroups(
213                                    user.getUserId(), QueryUtil.ALL_POS, QueryUtil.ALL_POS));
214    
215                    // User
216    
217                    if (!user.isDefaultUser()) {
218                            groups.add(user.getGroup());
219                    }
220    
221                    List<Group> groupsList = new ArrayList<>(groups);
222    
223                    Collections.sort(groupsList, orderByComparator);
224    
225                    return groupsList;
226            }
227    
228            public static WebDAVUtil getInstance() {
229                    PortalRuntimePermission.checkGetBeanProperty(WebDAVUtil.class);
230    
231                    return _instance;
232            }
233    
234            public static String getLockUuid(HttpServletRequest request)
235                    throws WebDAVException {
236    
237                    String token = StringPool.BLANK;
238    
239                    String value = GetterUtil.getString(request.getHeader("If"));
240    
241                    if (_log.isDebugEnabled()) {
242                            _log.debug("\"If\" header is " + value);
243                    }
244    
245                    if (value.contains("(<DAV:no-lock>)")) {
246                            if (_log.isWarnEnabled()) {
247                                    _log.warn("Lock tokens can never be <DAV:no-lock>");
248                            }
249    
250                            throw new WebDAVException();
251                    }
252    
253                    int beg = value.indexOf(TOKEN_PREFIX);
254    
255                    if (beg >= 0) {
256                            beg += TOKEN_PREFIX.length();
257    
258                            if (beg < value.length()) {
259                                    int end = value.indexOf(CharPool.GREATER_THAN, beg);
260    
261                                    token = GetterUtil.getString(value.substring(beg, end));
262                            }
263                    }
264    
265                    return token;
266            }
267    
268            public static String[] getPathArray(String path) {
269                    return getPathArray(path, false);
270            }
271    
272            public static String[] getPathArray(String path, boolean fixTrailing) {
273                    path = HttpUtil.fixPath(path, true, fixTrailing);
274    
275                    return StringUtil.split(path, CharPool.SLASH);
276            }
277    
278            public static String getResourceName(String[] pathArray) {
279                    if (pathArray.length <= 2) {
280                            return StringPool.BLANK;
281                    }
282                    else {
283                            return HttpUtil.decodeURL(pathArray[pathArray.length - 1]);
284                    }
285            }
286    
287            public static WebDAVStorage getStorage(String token) {
288                    return getInstance()._getStorage(token);
289            }
290    
291            public static Collection<String> getStorageTokens() {
292                    return getInstance()._getStorageTokens();
293            }
294    
295            public static long getTimeout(HttpServletRequest request) {
296                    final String TIME_PREFIX = "Second-";
297    
298                    long timeout = 0;
299    
300                    String value = GetterUtil.getString(request.getHeader("Timeout"));
301    
302                    if (_log.isDebugEnabled()) {
303                            _log.debug("\"Timeout\" header is " + value);
304                    }
305    
306                    int index = value.indexOf(TIME_PREFIX);
307    
308                    if (index >= 0) {
309                            index += TIME_PREFIX.length();
310    
311                            if (index < value.length()) {
312                                    timeout = GetterUtil.getLong(value.substring(index));
313                            }
314                    }
315    
316                    return timeout * Time.SECOND;
317            }
318    
319            public static boolean isOverwrite(HttpServletRequest request) {
320                    return getInstance()._isOverwrite(request);
321            }
322    
323            public static String stripManualCheckInRequiredPath(String url) {
324                    return stripToken(url, DL.MANUAL_CHECK_IN_REQUIRED_PATH);
325            }
326    
327            public static String stripOfficeExtension(String url) {
328                    String strippedUrl = stripToken(url, DL.OFFICE_EXTENSION_PATH);
329    
330                    if (strippedUrl.length() != url.length()) {
331                            strippedUrl = FileUtil.stripExtension(strippedUrl);
332                    }
333    
334                    return strippedUrl;
335            }
336    
337            public static String stripToken(String url, String token) {
338                    if (Validator.isNull(url)) {
339                            return StringPool.BLANK;
340                    }
341    
342                    int index = url.indexOf(token);
343    
344                    if (index >= 0) {
345                            url =
346                                    url.substring(0, index) + url.substring(index + token.length());
347                    }
348    
349                    return url;
350            }
351    
352            private WebDAVUtil() {
353                    Registry registry = RegistryUtil.getRegistry();
354    
355                    _serviceTracker = registry.trackServices(
356                            WebDAVStorage.class, new WebDAVStorageServiceTrackerCustomizer());
357    
358                    _serviceTracker.open();
359            }
360    
361            private void _addStorage(WebDAVStorage storage) {
362                    Registry registry = RegistryUtil.getRegistry();
363    
364                    ServiceRegistration<WebDAVStorage> serviceRegistration =
365                            registry.registerService(WebDAVStorage.class, storage);
366    
367                    _serviceRegistrations.put(storage, serviceRegistration);
368            }
369    
370            private void _deleteStorage(WebDAVStorage storage) {
371                    ServiceRegistration<WebDAVStorage> serviceRegistration =
372                            _serviceRegistrations.remove(storage);
373    
374                    if (serviceRegistration != null) {
375                            serviceRegistration.unregister();
376                    }
377            }
378    
379            private WebDAVStorage _getStorage(String token) {
380                    return _storageMap.get(token);
381            }
382    
383            private Collection<String> _getStorageTokens() {
384                    return _storageMap.keySet();
385            }
386    
387            private boolean _isOverwrite(HttpServletRequest request) {
388                    String value = GetterUtil.getString(request.getHeader("Overwrite"));
389    
390                    if (StringUtil.equalsIgnoreCase(value, "F") ||
391                            !GetterUtil.getBoolean(value)) {
392    
393                            return false;
394                    }
395                    else {
396                            return true;
397                    }
398            }
399    
400            private static final Log _log = LogFactoryUtil.getLog(WebDAVUtil.class);
401    
402            private static final WebDAVUtil _instance = new WebDAVUtil();
403    
404            private final ServiceRegistrationMap<WebDAVStorage> _serviceRegistrations =
405                    new ServiceRegistrationMap<>();
406            private final ServiceTracker<WebDAVStorage, WebDAVStorage> _serviceTracker;
407            private final Map<String, WebDAVStorage> _storageMap =
408                    new ConcurrentSkipListMap<>();
409    
410            private class WebDAVStorageServiceTrackerCustomizer
411                    implements ServiceTrackerCustomizer<WebDAVStorage, WebDAVStorage> {
412    
413                    @Override
414                    public WebDAVStorage addingService(
415                            ServiceReference<WebDAVStorage> serviceReference) {
416    
417                            Registry registry = RegistryUtil.getRegistry();
418    
419                            WebDAVStorage webDAVStorage = registry.getService(serviceReference);
420    
421                            if (webDAVStorage.getToken() == null) {
422                                    return null;
423                            }
424    
425                            _storageMap.put(webDAVStorage.getToken(), webDAVStorage);
426    
427                            return webDAVStorage;
428                    }
429    
430                    @Override
431                    public void modifiedService(
432                            ServiceReference<WebDAVStorage> serviceReference,
433                            WebDAVStorage webDAVStorage) {
434                    }
435    
436                    @Override
437                    public void removedService(
438                            ServiceReference<WebDAVStorage> serviceReference,
439                            WebDAVStorage webDAVStorage) {
440    
441                            Registry registry = RegistryUtil.getRegistry();
442    
443                            registry.ungetService(serviceReference);
444    
445                            _storageMap.remove(webDAVStorage.getToken());
446                    }
447    
448            }
449    
450    }