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.webserver;
016    
017    import com.liferay.portal.NoSuchGroupException;
018    import com.liferay.portal.freemarker.FreeMarkerUtil;
019    import com.liferay.portal.kernel.exception.PortalException;
020    import com.liferay.portal.kernel.exception.SystemException;
021    import com.liferay.portal.kernel.freemarker.FreeMarkerContext;
022    import com.liferay.portal.kernel.freemarker.FreeMarkerEngineUtil;
023    import com.liferay.portal.kernel.image.ImageBag;
024    import com.liferay.portal.kernel.image.ImageToolUtil;
025    import com.liferay.portal.kernel.log.Log;
026    import com.liferay.portal.kernel.log.LogFactoryUtil;
027    import com.liferay.portal.kernel.repository.RepositoryException;
028    import com.liferay.portal.kernel.repository.model.FileEntry;
029    import com.liferay.portal.kernel.repository.model.FileVersion;
030    import com.liferay.portal.kernel.repository.model.Folder;
031    import com.liferay.portal.kernel.servlet.HttpHeaders;
032    import com.liferay.portal.kernel.servlet.PortalSessionThreadLocal;
033    import com.liferay.portal.kernel.servlet.Range;
034    import com.liferay.portal.kernel.servlet.ServletResponseUtil;
035    import com.liferay.portal.kernel.util.CharPool;
036    import com.liferay.portal.kernel.util.ContentTypes;
037    import com.liferay.portal.kernel.util.FastDateFormatFactoryUtil;
038    import com.liferay.portal.kernel.util.FileUtil;
039    import com.liferay.portal.kernel.util.GetterUtil;
040    import com.liferay.portal.kernel.util.HttpUtil;
041    import com.liferay.portal.kernel.util.MimeTypesUtil;
042    import com.liferay.portal.kernel.util.ParamUtil;
043    import com.liferay.portal.kernel.util.ReleaseInfo;
044    import com.liferay.portal.kernel.util.SetUtil;
045    import com.liferay.portal.kernel.util.StringPool;
046    import com.liferay.portal.kernel.util.StringUtil;
047    import com.liferay.portal.kernel.util.Validator;
048    import com.liferay.portal.kernel.util.Validator_IW;
049    import com.liferay.portal.kernel.webdav.WebDAVUtil;
050    import com.liferay.portal.model.Company;
051    import com.liferay.portal.model.Group;
052    import com.liferay.portal.model.Image;
053    import com.liferay.portal.model.ImageConstants;
054    import com.liferay.portal.model.User;
055    import com.liferay.portal.model.impl.ImageImpl;
056    import com.liferay.portal.repository.liferayrepository.model.LiferayFileEntry;
057    import com.liferay.portal.repository.liferayrepository.model.LiferayFileVersion;
058    import com.liferay.portal.security.auth.PrincipalException;
059    import com.liferay.portal.security.auth.PrincipalThreadLocal;
060    import com.liferay.portal.security.permission.PermissionChecker;
061    import com.liferay.portal.security.permission.PermissionCheckerFactoryUtil;
062    import com.liferay.portal.security.permission.PermissionThreadLocal;
063    import com.liferay.portal.service.CompanyLocalServiceUtil;
064    import com.liferay.portal.service.GroupLocalServiceUtil;
065    import com.liferay.portal.service.ImageLocalServiceUtil;
066    import com.liferay.portal.service.ImageServiceUtil;
067    import com.liferay.portal.service.UserLocalServiceUtil;
068    import com.liferay.portal.theme.ThemeDisplay;
069    import com.liferay.portal.util.Portal;
070    import com.liferay.portal.util.PortalUtil;
071    import com.liferay.portal.util.PropsValues;
072    import com.liferay.portal.util.WebKeys;
073    import com.liferay.portlet.documentlibrary.NoSuchFileEntryException;
074    import com.liferay.portlet.documentlibrary.NoSuchFolderException;
075    import com.liferay.portlet.documentlibrary.model.DLFileEntry;
076    import com.liferay.portlet.documentlibrary.model.DLFileEntryMetadata;
077    import com.liferay.portlet.documentlibrary.model.DLFileShortcut;
078    import com.liferay.portlet.documentlibrary.model.DLFolderConstants;
079    import com.liferay.portlet.documentlibrary.service.DLAppLocalServiceUtil;
080    import com.liferay.portlet.documentlibrary.service.DLAppServiceUtil;
081    import com.liferay.portlet.documentlibrary.service.DLFileEntryMetadataLocalServiceUtil;
082    import com.liferay.portlet.documentlibrary.service.DLFileEntryServiceUtil;
083    import com.liferay.portlet.documentlibrary.util.AudioProcessorUtil;
084    import com.liferay.portlet.documentlibrary.util.DLUtil;
085    import com.liferay.portlet.documentlibrary.util.DocumentConversionUtil;
086    import com.liferay.portlet.documentlibrary.util.ImageProcessorUtil;
087    import com.liferay.portlet.documentlibrary.util.PDFProcessor;
088    import com.liferay.portlet.documentlibrary.util.PDFProcessorUtil;
089    import com.liferay.portlet.documentlibrary.util.VideoProcessor;
090    import com.liferay.portlet.documentlibrary.util.VideoProcessorUtil;
091    import com.liferay.portlet.dynamicdatalists.model.DDLRecord;
092    import com.liferay.portlet.dynamicdatalists.service.DDLRecordLocalServiceUtil;
093    import com.liferay.portlet.dynamicdatamapping.storage.Field;
094    import com.liferay.portlet.dynamicdatamapping.storage.Fields;
095    import com.liferay.portlet.dynamicdatamapping.storage.StorageEngineUtil;
096    import com.liferay.portlet.dynamicdatamapping.util.DDMUtil;
097    
098    import java.awt.image.RenderedImage;
099    
100    import java.io.File;
101    import java.io.FileInputStream;
102    import java.io.IOException;
103    import java.io.InputStream;
104    
105    import java.text.Format;
106    
107    import java.util.ArrayList;
108    import java.util.Date;
109    import java.util.List;
110    import java.util.Set;
111    
112    import javax.servlet.ServletConfig;
113    import javax.servlet.ServletException;
114    import javax.servlet.http.HttpServlet;
115    import javax.servlet.http.HttpServletRequest;
116    import javax.servlet.http.HttpServletResponse;
117    import javax.servlet.http.HttpSession;
118    
119    /**
120     * @author Alexander Chow
121     * @author Brian Wing Shun Chan
122     */
123    public class WebServerServlet extends HttpServlet {
124    
125            /**
126             * @see com.liferay.portal.servlet.filters.virtualhost.VirtualHostFilter
127             */
128            public static boolean hasFiles(HttpServletRequest request) {
129                    try {
130    
131                            // Do not use permission checking since this may be called from
132                            // other contexts that are also managing the principal
133    
134                            User user = _getUser(request);
135    
136                            String path = HttpUtil.fixPath(request.getPathInfo());
137    
138                            String[] pathArray = StringUtil.split(path, CharPool.SLASH);
139    
140                            if (pathArray.length == 0) {
141                                    return true;
142                            }
143                            else if (_PATH_DDM.equals(pathArray[0])) {
144                                    _checkDDMRecord(pathArray);
145                            }
146                            else if (Validator.isNumber(pathArray[0])) {
147                                    _checkFileEntry(pathArray);
148                            }
149                            else {
150                                    long groupId = _getGroupId(user.getCompanyId(), pathArray[0]);
151                                    long folderId = DLFolderConstants.DEFAULT_PARENT_FOLDER_ID;
152    
153                                    for (int i = 1; i < pathArray.length; i++) {
154                                            try {
155                                                    Folder folder = DLAppLocalServiceUtil.getFolder(
156                                                            groupId, folderId, pathArray[i]);
157    
158                                                    folderId = folder.getFolderId();
159                                            }
160                                            catch (NoSuchFolderException nsfe) {
161                                                    if (i != (pathArray.length - 1)) {
162                                                            return false;
163                                                    }
164    
165                                                    pathArray = new String[] {
166                                                            String.valueOf(groupId), String.valueOf(folderId),
167                                                            pathArray[i]
168                                                    };
169    
170                                                    _checkFileEntry(pathArray);
171                                            }
172                                    }
173                            }
174                    }
175                    catch (Exception e) {
176                            return false;
177                    }
178    
179                    return true;
180            }
181    
182            @Override
183            public void init(ServletConfig servletConfig) throws ServletException {
184                    super.init(servletConfig);
185    
186                    _lastModified = GetterUtil.getBoolean(
187                            servletConfig.getInitParameter("last_modified"), true);
188            }
189    
190            @Override
191            public void service(
192                            HttpServletRequest request, HttpServletResponse response)
193                    throws IOException, ServletException {
194    
195                    User user = null;
196    
197                    try {
198                            user = _getUser(request);
199    
200                            PrincipalThreadLocal.setName(user.getUserId());
201                            PrincipalThreadLocal.setPassword(
202                                    PortalUtil.getUserPassword(request));
203    
204                            PermissionChecker permissionChecker =
205                                    PermissionCheckerFactoryUtil.create(user);
206    
207                            PermissionThreadLocal.setPermissionChecker(permissionChecker);
208    
209                            if (_lastModified) {
210                                    long lastModified = getLastModified(request);
211    
212                                    if (lastModified > 0) {
213                                            long ifModifiedSince = request.getDateHeader(
214                                                    HttpHeaders.IF_MODIFIED_SINCE);
215    
216                                            if ((ifModifiedSince > 0) &&
217                                                    (ifModifiedSince == lastModified)) {
218    
219                                                    response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
220    
221                                                    return;
222                                            }
223                                    }
224    
225                                    if (lastModified > 0) {
226                                            response.setDateHeader(
227                                                    HttpHeaders.LAST_MODIFIED, lastModified);
228                                    }
229                            }
230    
231                            String path = HttpUtil.fixPath(request.getPathInfo());
232                            String[] pathArray = StringUtil.split(path, CharPool.SLASH);
233    
234                            if (pathArray.length == 0) {
235                                    sendGroups(
236                                            response, user,
237                                            request.getServletPath() + StringPool.SLASH + path);
238                            }
239                            else {
240                                    if (_PATH_DDM.equals(pathArray[0])) {
241                                            sendDDMRecordFile(request, response, pathArray);
242                                    }
243                                    else if (Validator.isNumber(pathArray[0])) {
244                                            sendFile(request, response, user, pathArray);
245                                    }
246                                    else {
247                                            if (isLegacyImageGalleryImageId(request, response)) {
248                                                    return;
249                                            }
250    
251                                            Image image = getImage(request, true);
252    
253                                            if (image != null) {
254                                                    writeImage(image, request, response);
255                                            }
256                                            else {
257                                                    sendDocumentLibrary(
258                                                            request, response, user,
259                                                            request.getServletPath() + StringPool.SLASH + path,
260                                                            pathArray);
261                                            }
262                                    }
263                            }
264                    }
265                    catch (NoSuchFileEntryException nsfee) {
266                            PortalUtil.sendError(
267                                    HttpServletResponse.SC_NOT_FOUND, nsfee, request, response);
268                    }
269                    catch (PrincipalException pe) {
270                            processPrincipalException(pe, user, request, response);
271                    }
272                    catch (Exception e) {
273                            PortalUtil.sendError(e, request, response);
274                    }
275            }
276    
277            protected Image convertFileEntry(boolean smallImage, FileEntry fileEntry)
278                    throws PortalException, SystemException {
279    
280                    try {
281                            Image image = new ImageImpl();
282    
283                            image.setModifiedDate(fileEntry.getModifiedDate());
284    
285                            InputStream is = null;
286    
287                            if (smallImage) {
288                                    is = ImageProcessorUtil.getThumbnailAsStream(
289                                            fileEntry.getFileVersion(), 0);
290                            }
291                            else {
292                                    is = fileEntry.getContentStream();
293                            }
294    
295                            byte[] bytes = FileUtil.getBytes(is);
296    
297                            image.setTextObj(bytes);
298    
299                            image.setType(fileEntry.getExtension());
300    
301                            return image;
302                    }
303                    catch (PortalException pe) {
304                            throw pe;
305                    }
306                    catch (SystemException se) {
307                            throw se;
308                    }
309                    catch (Exception e) {
310                            throw new SystemException(e);
311                    }
312            }
313    
314            protected Image getDefaultImage(HttpServletRequest request, long imageId) {
315                    String path = GetterUtil.getString(request.getPathInfo());
316    
317                    if (path.startsWith("/company_logo") ||
318                            path.startsWith("/layout_set_logo") || path.startsWith("/logo")) {
319    
320                            return ImageLocalServiceUtil.getDefaultCompanyLogo();
321                    }
322                    else if (path.startsWith("/organization_logo")) {
323                            return ImageLocalServiceUtil.getDefaultOrganizationLogo();
324                    }
325                    else if (path.startsWith("/user_female_portrait")) {
326                            return ImageLocalServiceUtil.getDefaultUserFemalePortrait();
327                    }
328                    else if (path.startsWith("/user_male_portrait")) {
329                            return ImageLocalServiceUtil.getDefaultUserMalePortrait();
330                    }
331                    else if (path.startsWith("/user_portrait")) {
332                            return ImageLocalServiceUtil.getDefaultUserMalePortrait();
333                    }
334                    else {
335                            return null;
336                    }
337            }
338    
339            protected FileEntry getFileEntry(String[] pathArray) throws Exception {
340                    if (pathArray.length == 1) {
341                            long dlFileShortcutId = GetterUtil.getLong(pathArray[0]);
342    
343                            DLFileShortcut dlFileShortcut = DLAppServiceUtil.getFileShortcut(
344                                    dlFileShortcutId);
345    
346                            return DLAppServiceUtil.getFileEntry(
347                                    dlFileShortcut.getToFileEntryId());
348                    }
349                    else if (pathArray.length == 2) {
350                            long groupId = GetterUtil.getLong(pathArray[0]);
351    
352                            return DLAppServiceUtil.getFileEntryByUuidAndGroupId(
353                                    pathArray[1], groupId);
354                    }
355                    else if (pathArray.length == 3) {
356                            long groupId = GetterUtil.getLong(pathArray[0]);
357                            long folderId = GetterUtil.getLong(pathArray[1]);
358                            String fileName = HttpUtil.decodeURL(pathArray[2]);
359    
360                            if (fileName.contains(StringPool.QUESTION)) {
361                                    fileName = fileName.substring(
362                                            0, fileName.indexOf(StringPool.QUESTION));
363                            }
364    
365                            return DLAppServiceUtil.getFileEntry(groupId, folderId, fileName);
366                    }
367                    else {
368                            long groupId = GetterUtil.getLong(pathArray[0]);
369    
370                            String uuid = pathArray[3];
371    
372                            return DLAppServiceUtil.getFileEntryByUuidAndGroupId(uuid, groupId);
373                    }
374            }
375    
376            protected Image getImage(HttpServletRequest request, boolean getDefault)
377                    throws PortalException, SystemException {
378    
379                    Image image = null;
380    
381                    long imageId = getImageId(request);
382    
383                    if (imageId > 0) {
384                            image = ImageServiceUtil.getImage(imageId);
385    
386                            String path = GetterUtil.getString(request.getPathInfo());
387    
388                            if (path.startsWith("/user_female_portrait") ||
389                                    path.startsWith("/user_male_portrait") ||
390                                    path.startsWith("/user_portrait")) {
391    
392                                    image = getUserPortraitImageResized(image, imageId);
393                            }
394                    }
395                    else {
396                            String uuid = ParamUtil.getString(request, "uuid");
397                            long groupId = ParamUtil.getLong(request, "groupId");
398                            boolean igSmallImage = ParamUtil.getBoolean(
399                                    request, "igSmallImage");
400    
401                            if (Validator.isNotNull(uuid) && (groupId > 0)) {
402                                    try {
403                                            FileEntry fileEntry =
404                                                    DLAppServiceUtil.getFileEntryByUuidAndGroupId(
405                                                            uuid, groupId);
406    
407                                            image = convertFileEntry(igSmallImage, fileEntry);
408                                    }
409                                    catch (Exception e) {
410                                    }
411                            }
412                    }
413    
414                    if (getDefault) {
415                            if (image == null) {
416                                    if (_log.isWarnEnabled()) {
417                                            _log.warn("Get a default image for " + imageId);
418                                    }
419    
420                                    image = getDefaultImage(request, imageId);
421                            }
422                    }
423    
424                    return image;
425            }
426    
427            protected byte[] getImageBytes(HttpServletRequest request, Image image) {
428                    try {
429                            if (!PropsValues.IMAGE_AUTO_SCALE) {
430                                    return image.getTextObj();
431                            }
432    
433                            ImageBag imageBag = null;
434    
435                            if (image.getImageId() == 0) {
436                                    imageBag = ImageToolUtil.read(image.getTextObj());
437    
438                                    RenderedImage renderedImage = imageBag.getRenderedImage();
439    
440                                    image.setHeight(renderedImage.getHeight());
441                                    image.setWidth(renderedImage.getWidth());
442                            }
443    
444                            int height = ParamUtil.getInteger(
445                                    request, "height", image.getHeight());
446                            int width = ParamUtil.getInteger(
447                                    request, "width", image.getWidth());
448    
449                            if ((height >= image.getHeight()) && (width >= image.getWidth())) {
450                                    return image.getTextObj();
451                            }
452    
453                            if (image.getImageId() != 0) {
454                                    imageBag = ImageToolUtil.read(image.getTextObj());
455                            }
456    
457                            RenderedImage renderedImage = ImageToolUtil.scale(
458                                    imageBag.getRenderedImage(), height, width);
459    
460                            return ImageToolUtil.getBytes(renderedImage, imageBag.getType());
461                    }
462                    catch (Exception e) {
463                            if (_log.isWarnEnabled()) {
464                                    _log.warn("Error scaling image " + image.getImageId(), e);
465                            }
466                    }
467    
468                    return image.getTextObj();
469            }
470    
471            protected long getImageId(HttpServletRequest request) {
472    
473                    // The image id may be passed in as image_id, img_id, or i_id
474    
475                    long imageId = ParamUtil.getLong(request, "image_id");
476    
477                    if (imageId <= 0) {
478                            imageId = ParamUtil.getLong(request, "img_id");
479                    }
480    
481                    if (imageId <= 0) {
482                            imageId = ParamUtil.getLong(request, "i_id");
483                    }
484    
485                    if (imageId <= 0) {
486                            long companyId = ParamUtil.getLong(request, "companyId");
487                            String screenName = ParamUtil.getString(request, "screenName");
488    
489                            try {
490                                    if ((companyId > 0) && Validator.isNotNull(screenName)) {
491                                            User user = UserLocalServiceUtil.getUserByScreenName(
492                                                    companyId, screenName);
493    
494                                            imageId = user.getPortraitId();
495                                    }
496                            }
497                            catch (Exception e) {
498                            }
499                    }
500    
501                    return imageId;
502            }
503    
504            @Override
505            protected long getLastModified(HttpServletRequest request) {
506                    try {
507                            Date modifiedDate = null;
508    
509                            Image image = getImage(request, true);
510    
511                            if (image != null) {
512                                    modifiedDate = image.getModifiedDate();
513                            }
514                            else {
515                                    String path = HttpUtil.fixPath(request.getPathInfo());
516    
517                                    String[] pathArray = StringUtil.split(path, CharPool.SLASH);
518    
519                                    if (pathArray.length == 0) {
520                                            return -1;
521                                    }
522    
523                                    if (pathArray[0].equals("language")) {
524                                            return -1;
525                                    }
526    
527                                    FileEntry fileEntry = null;
528    
529                                    try {
530                                            fileEntry = getFileEntry(pathArray);
531                                    }
532                                    catch (Exception e) {
533                                    }
534    
535                                    if (fileEntry == null) {
536                                            return -1;
537                                    }
538                                    else {
539                                            String version = ParamUtil.getString(request, "version");
540    
541                                            if (Validator.isNotNull(version)) {
542                                                    FileVersion fileVersion = fileEntry.getFileVersion(
543                                                            version);
544    
545                                                    modifiedDate = fileVersion.getModifiedDate();
546                                            }
547                                            else {
548                                                    modifiedDate = fileEntry.getModifiedDate();
549                                            }
550                                    }
551                            }
552    
553                            if (modifiedDate == null) {
554                                    modifiedDate = PortalUtil.getUptime();
555                            }
556    
557                            // Round down and remove milliseconds
558    
559                            return (modifiedDate.getTime() / 1000) * 1000;
560                    }
561                    catch (PrincipalException pe) {
562                            if (_log.isWarnEnabled()) {
563                                    _log.warn(pe, pe);
564                            }
565                    }
566                    catch (Exception e) {
567                            _log.error(e, e);
568                    }
569    
570                    return -1;
571            }
572    
573            protected Image getUserPortraitImageResized(Image image, long imageId)
574                    throws PortalException, SystemException {
575    
576                    if (image == null) {
577                            return null;
578                    }
579    
580                    if ((image.getHeight() > PropsValues.USERS_IMAGE_MAX_HEIGHT) ||
581                            (image.getWidth() > PropsValues.USERS_IMAGE_MAX_WIDTH)) {
582    
583                            User user = UserLocalServiceUtil.getUserByPortraitId(imageId);
584    
585                            UserLocalServiceUtil.updatePortrait(
586                                    user.getUserId(), image.getTextObj());
587    
588                            return ImageLocalServiceUtil.getImage(imageId);
589                    }
590    
591                    return image;
592            }
593    
594            protected boolean isLegacyImageGalleryImageId(
595                    HttpServletRequest request, HttpServletResponse response) {
596    
597                    try {
598                            long imageId = getImageId(request);
599    
600                            if (imageId == 0) {
601                                    return false;
602                            }
603    
604                            DLFileEntry dlFileEntry =
605                                    DLFileEntryServiceUtil.fetchFileEntryByImageId(imageId);
606    
607                            if (dlFileEntry == null) {
608                                    return false;
609                            }
610    
611                            ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(
612                                    WebKeys.THEME_DISPLAY);
613    
614                            String queryString = StringPool.BLANK;
615    
616                            if (imageId == dlFileEntry.getSmallImageId()) {
617                                    queryString = "&imageThumbnail=1";
618                            }
619                            else if (imageId == dlFileEntry.getSmallImageId()) {
620                                    queryString = "&imageThumbnail=2";
621                            }
622                            else if (imageId == dlFileEntry.getSmallImageId()) {
623                                    queryString = "&imageThumbnail=3";
624                            }
625    
626                            String url = DLUtil.getPreviewURL(
627                                    new LiferayFileEntry(dlFileEntry),
628                                    new LiferayFileVersion(dlFileEntry.getFileVersion()),
629                                    themeDisplay, queryString);
630    
631                            response.setHeader(HttpHeaders.LOCATION, url);
632                            response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
633    
634                            return true;
635                    }
636                    catch (Exception e) {
637                    }
638    
639                    return false;
640            }
641    
642            protected boolean isSupportsRangeHeader(String contentType) {
643                    return _acceptRangesMimeTypes.contains(contentType);
644            }
645    
646            protected void processPrincipalException(
647                            Throwable t, User user, HttpServletRequest request,
648                            HttpServletResponse response)
649                    throws IOException, ServletException {
650    
651                    if (!user.isDefaultUser()) {
652                            PortalUtil.sendError(
653                                    HttpServletResponse.SC_UNAUTHORIZED, (Exception)t, request,
654                                    response);
655    
656                            return;
657                    }
658    
659                    String redirect =
660                            request.getContextPath() + Portal.PATH_MAIN + "/portal/login";
661    
662                    String currentURL = PortalUtil.getCurrentURL(request);
663    
664                    redirect = HttpUtil.addParameter(redirect, "redirect", currentURL);
665    
666                    response.sendRedirect(redirect);
667            }
668    
669            protected void sendDDMRecordFile(
670                            HttpServletRequest request, HttpServletResponse response,
671                            String[] pathArray)
672                    throws Exception {
673    
674                    if (pathArray.length == 4) {
675                            String className = GetterUtil.getString(pathArray[1]);
676                            long classPK = GetterUtil.getLong(pathArray[2]);
677                            String fieldName = GetterUtil.getString(pathArray[3]);
678    
679                            Field field = null;
680    
681                            if (className.equals(DDLRecord.class.getName())) {
682                                    DDLRecord ddlRecord = DDLRecordLocalServiceUtil.getRecord(
683                                            classPK);
684    
685                                    field = ddlRecord.getField(fieldName);
686                            }
687                            else if (className.equals(DLFileEntryMetadata.class.getName())) {
688                                    DLFileEntryMetadata fileEntryMetadata =
689                                            DLFileEntryMetadataLocalServiceUtil.getDLFileEntryMetadata(
690                                                    classPK);
691    
692                                    Fields fields = StorageEngineUtil.getFields(
693                                            fileEntryMetadata.getDDMStorageId());
694    
695                                    field = fields.get(fieldName);
696                            }
697    
698                            DDMUtil.sendFieldFile(request, response, field);
699                    }
700            }
701    
702            protected void sendDocumentLibrary(
703                            HttpServletRequest request, HttpServletResponse response, User user,
704                            String path, String[] pathArray)
705                    throws Exception {
706    
707                    if (!PropsValues.WEB_SERVER_SERVLET_DIRECTORY_INDEXING_ENABLED) {
708                            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
709    
710                            return;
711                    }
712    
713                    long groupId = _getGroupId(user.getCompanyId(), pathArray[0]);
714                    long folderId = DLFolderConstants.DEFAULT_PARENT_FOLDER_ID;
715    
716                    for (int i = 1; i < pathArray.length; i++) {
717                            String name = pathArray[i];
718    
719                            try {
720                                    Folder folder = DLAppServiceUtil.getFolder(
721                                            groupId, folderId, name);
722    
723                                    folderId = folder.getFolderId();
724                            }
725                            catch (NoSuchFolderException nsfe) {
726                                    if (i != (pathArray.length - 1)) {
727                                            throw nsfe;
728                                    }
729    
730                                    String title = name;
731    
732                                    sendFile(response, user, groupId, folderId, title);
733    
734                                    return;
735                            }
736                    }
737    
738                    try {
739                            sendFile(response, user, groupId, folderId, "index.html");
740    
741                            return;
742                    }
743                    catch (Exception e) {
744                            if ((e instanceof NoSuchFileEntryException) ||
745                                    (e instanceof PrincipalException)) {
746    
747                                    try {
748                                            sendFile(response, user, groupId, folderId, "index.htm");
749    
750                                            return;
751                                    }
752                                    catch (NoSuchFileEntryException nsfee) {
753                                    }
754                                    catch (PrincipalException pe) {
755                                    }
756                            }
757                            else {
758                                    throw e;
759                            }
760                    }
761    
762                    List<WebServerEntry> webServerEntries = new ArrayList<WebServerEntry>();
763    
764                    webServerEntries.add(new WebServerEntry(path, "../"));
765    
766                    List<Folder> folders = DLAppServiceUtil.getFolders(groupId, folderId);
767    
768                    for (Folder folder : folders) {
769                            WebServerEntry webServerEntry = new WebServerEntry(
770                                    path, folder.getName() + StringPool.SLASH,
771                                    folder.getCreateDate(), folder.getModifiedDate(),
772                                    folder.getDescription(), 0);
773    
774                            webServerEntries.add(webServerEntry);
775                    }
776    
777                    List<FileEntry> fileEntries = DLAppServiceUtil.getFileEntries(
778                            groupId, folderId);
779    
780                    for (FileEntry fileEntry : fileEntries) {
781                            WebServerEntry webServerEntry = new WebServerEntry(
782                                    path, fileEntry.getTitle(), fileEntry.getCreateDate(),
783                                    fileEntry.getModifiedDate(), fileEntry.getDescription(),
784                                    fileEntry.getSize());
785    
786                            webServerEntries.add(webServerEntry);
787                    }
788    
789                    sendHTML(response, path, webServerEntries);
790            }
791    
792            protected void sendFile(
793                            HttpServletRequest request, HttpServletResponse response, User user,
794                            String[] pathArray)
795                    throws Exception {
796    
797                    // Retrieve file details
798    
799                    FileEntry fileEntry = getFileEntry(pathArray);
800    
801                    if (fileEntry == null) {
802                            throw new NoSuchFileEntryException();
803                    }
804    
805                    String version = ParamUtil.getString(request, "version");
806    
807                    if (Validator.isNull(version)) {
808                            if (Validator.isNotNull(fileEntry.getVersion())) {
809                                    version = fileEntry.getVersion();
810                            }
811                    }
812    
813                    String tempFileId = DLUtil.getTempFileId(
814                            fileEntry.getFileEntryId(), version);
815    
816                    FileVersion fileVersion = fileEntry.getFileVersion(version);
817    
818                    String fileName = fileVersion.getTitle();
819    
820                    String extension = fileVersion.getExtension();
821    
822                    if (Validator.isNotNull(extension) &&
823                            !fileName.endsWith(StringPool.PERIOD + extension)) {
824    
825                            fileName += StringPool.PERIOD + extension;
826                    }
827    
828                    // Handle requested conversion
829    
830                    boolean converted = false;
831    
832                    String targetExtension = ParamUtil.getString(
833                            request, "targetExtension");
834                    int imageThumbnail = ParamUtil.getInteger(request, "imageThumbnail");
835                    int documentThumbnail = ParamUtil.getInteger(
836                            request, "documentThumbnail");
837                    int previewFileIndex = ParamUtil.getInteger(
838                            request, "previewFileIndex");
839                    boolean audioPreview = ParamUtil.getBoolean(request, "audioPreview");
840                    boolean imagePreview = ParamUtil.getBoolean(request, "imagePreview");
841                    boolean videoPreview = ParamUtil.getBoolean(request, "videoPreview");
842                    int videoThumbnail = ParamUtil.getInteger(request, "videoThumbnail");
843    
844                    InputStream inputStream = null;
845                    long contentLength = 0;
846    
847                    if ((imageThumbnail > 0) && (imageThumbnail <= 3)) {
848                            fileName = FileUtil.stripExtension(fileName).concat(
849                                    StringPool.PERIOD).concat(
850                                            ImageProcessorUtil.getThumbnailType(fileVersion));
851    
852                            int thumbnailIndex = imageThumbnail - 1;
853    
854                            inputStream = ImageProcessorUtil.getThumbnailAsStream(
855                                    fileVersion, thumbnailIndex);
856                            contentLength = ImageProcessorUtil.getThumbnailFileSize(
857                                    fileVersion, thumbnailIndex);
858    
859                            converted = true;
860                    }
861                    else if ((documentThumbnail > 0) && (documentThumbnail <= 3)) {
862                            fileName = FileUtil.stripExtension(fileName).concat(
863                                    StringPool.PERIOD).concat(PDFProcessor.THUMBNAIL_TYPE);
864    
865                            int thumbnailIndex = documentThumbnail - 1;
866    
867                            inputStream = PDFProcessorUtil.getThumbnailAsStream(
868                                    fileVersion, thumbnailIndex);
869                            contentLength = PDFProcessorUtil.getThumbnailFileSize(
870                                    fileVersion, thumbnailIndex);
871    
872                            converted = true;
873                    }
874                    else if (previewFileIndex > 0) {
875                            fileName = FileUtil.stripExtension(fileName).concat(
876                                    StringPool.PERIOD).concat(PDFProcessor.PREVIEW_TYPE);
877                            inputStream = PDFProcessorUtil.getPreviewAsStream(
878                                    fileVersion, previewFileIndex);
879                            contentLength = PDFProcessorUtil.getPreviewFileSize(
880                                    fileVersion, previewFileIndex);
881    
882                            converted = true;
883                    }
884                    else if (audioPreview || videoPreview) {
885                            String type = ParamUtil.getString(request, "type");
886    
887                            fileName = FileUtil.stripExtension(fileName).concat(
888                                    StringPool.PERIOD).concat(type);
889    
890                            if (audioPreview) {
891                                    inputStream = AudioProcessorUtil.getPreviewAsStream(
892                                            fileVersion, type);
893                                    contentLength = AudioProcessorUtil.getPreviewFileSize(
894                                            fileVersion, type);
895                            }
896                            else {
897                                    inputStream = VideoProcessorUtil.getPreviewAsStream(
898                                            fileVersion, type);
899                                    contentLength = VideoProcessorUtil.getPreviewFileSize(
900                                            fileVersion, type);
901                            }
902    
903                            converted = true;
904                    }
905                    else if (imagePreview) {
906                            String type = ImageProcessorUtil.getPreviewType(fileVersion);
907    
908                            fileName = FileUtil.stripExtension(fileName).concat(
909                                    StringPool.PERIOD).concat(type);
910    
911                            inputStream = ImageProcessorUtil.getPreviewAsStream(fileVersion);
912    
913                            contentLength = ImageProcessorUtil.getPreviewFileSize(fileVersion);
914    
915                            converted = true;
916                    }
917                    else if ((videoThumbnail > 0) && (videoThumbnail <= 3)) {
918                            fileName = FileUtil.stripExtension(fileName).concat(
919                                    StringPool.PERIOD).concat(VideoProcessor.THUMBNAIL_TYPE);
920    
921                            int thumbnailIndex = videoThumbnail - 1;
922    
923                            inputStream = VideoProcessorUtil.getThumbnailAsStream(
924                                    fileVersion, thumbnailIndex);
925                            contentLength = VideoProcessorUtil.getThumbnailFileSize(
926                                    fileVersion, thumbnailIndex);
927    
928                            converted = true;
929                    }
930                    else {
931                            inputStream = fileVersion.getContentStream(true);
932                            contentLength = fileVersion.getSize();
933    
934                            if (Validator.isNotNull(targetExtension)) {
935                                    File convertedFile = DocumentConversionUtil.convert(
936                                            tempFileId, inputStream, extension, targetExtension);
937    
938                                    if (convertedFile != null) {
939                                            fileName = FileUtil.stripExtension(fileName).concat(
940                                                    StringPool.PERIOD).concat(targetExtension);
941                                            inputStream = new FileInputStream(convertedFile);
942                                            contentLength = convertedFile.length();
943    
944                                            converted = true;
945                                    }
946                            }
947                    }
948    
949                    // Determine proper content type
950    
951                    String contentType = null;
952    
953                    if (converted) {
954                            contentType = MimeTypesUtil.getContentType(fileName);
955                    }
956                    else {
957                            contentType = fileVersion.getMimeType();
958                    }
959    
960                    if (_log.isDebugEnabled()) {
961                            _log.debug("Content type set to " + contentType);
962                    }
963    
964                    // Send file
965    
966                    if (isSupportsRangeHeader(contentType)) {
967                            sendFileWithRangeHeader(
968                                    request, response, fileName, inputStream, contentLength,
969                                    contentType);
970                    }
971                    else {
972                            ServletResponseUtil.sendFile(
973                                    request, response, fileName, inputStream, contentLength,
974                                    contentType);
975                    }
976            }
977    
978            protected void sendFile(
979                            HttpServletResponse response, User user, long groupId,
980                            long folderId, String title)
981                    throws Exception {
982    
983                    FileEntry fileEntry = DLAppServiceUtil.getFileEntry(
984                            groupId, folderId, title);
985    
986                    String contentType = fileEntry.getMimeType();
987    
988                    response.setContentType(contentType);
989    
990                    InputStream inputStream = fileEntry.getContentStream();
991    
992                    ServletResponseUtil.write(response, inputStream);
993            }
994    
995            protected void sendFileWithRangeHeader(
996                            HttpServletRequest request, HttpServletResponse response,
997                            String fileName, InputStream inputStream, long contentLength,
998                            String contentType)
999                    throws IOException {
1000    
1001                    if (_log.isDebugEnabled()) {
1002                            _log.debug("Accepting ranges for the file " + fileName);
1003                    }
1004    
1005                    response.setHeader(
1006                            HttpHeaders.ACCEPT_RANGES, HttpHeaders.ACCEPT_RANGES_BYTES_VALUE);
1007    
1008                    List<Range> ranges = null;
1009    
1010                    try {
1011                            ranges = ServletResponseUtil.getRanges(
1012                                    request, response, contentLength);
1013                    }
1014                    catch (IOException ioe) {
1015                            if (_log.isErrorEnabled()) {
1016                                    _log.error(ioe);
1017                            }
1018    
1019                            response.setHeader(
1020                                    HttpHeaders.CONTENT_RANGE, "bytes */" + contentLength);
1021    
1022                            response.sendError(
1023                                    HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
1024    
1025                            return;
1026                    }
1027    
1028                    if ((ranges == null) || ranges.isEmpty()) {
1029                            ServletResponseUtil.sendFile(
1030                                    request, response, fileName, inputStream, contentLength,
1031                                    contentType);
1032                    }
1033                    else {
1034                            if (_log.isDebugEnabled()) {
1035                                    _log.debug(
1036                                            "Request has range header " +
1037                                                    request.getHeader(HttpHeaders.RANGE));
1038                            }
1039    
1040                            ServletResponseUtil.write(
1041                                    request, response, fileName, ranges, inputStream, contentLength,
1042                                    contentType);
1043                    }
1044            }
1045    
1046            protected void sendGroups(
1047                            HttpServletResponse response, User user, String path)
1048                    throws Exception {
1049    
1050                    if (!PropsValues.WEB_SERVER_SERVLET_DIRECTORY_INDEXING_ENABLED) {
1051                            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
1052    
1053                            return;
1054                    }
1055    
1056                    List<WebServerEntry> webServerEntries = new ArrayList<WebServerEntry>();
1057    
1058                    List<Group> groups = WebDAVUtil.getGroups(user);
1059    
1060                    for (Group group : groups) {
1061                            String name = HttpUtil.fixPath(group.getFriendlyURL());
1062    
1063                            WebServerEntry webServerEntry = new WebServerEntry(
1064                                    path, name + StringPool.SLASH, null, null,
1065                                    group.getDescription(), 0);
1066    
1067                            webServerEntries.add(webServerEntry);
1068                    }
1069    
1070                    sendHTML(response, path, webServerEntries);
1071            }
1072    
1073            protected void sendHTML(
1074                            HttpServletResponse response, String path,
1075                            List<WebServerEntry> webServerEntries)
1076                    throws Exception {
1077    
1078                    FreeMarkerContext freeMarkerContext =
1079                            FreeMarkerEngineUtil.getWrappedRestrictedToolsContext();
1080    
1081                    freeMarkerContext.put("dateFormat", _dateFormat);
1082                    freeMarkerContext.put("entries", webServerEntries);
1083                    freeMarkerContext.put("path", HttpUtil.encodePath(path));
1084    
1085                    if (_WEB_SERVER_SERVLET_VERSION_VERBOSITY_DEFAULT) {
1086                    }
1087                    else if (_WEB_SERVER_SERVLET_VERSION_VERBOSITY_PARTIAL) {
1088                            freeMarkerContext.put("releaseInfo", ReleaseInfo.getName());
1089                    }
1090                    else {
1091                            freeMarkerContext.put("releaseInfo", ReleaseInfo.getReleaseInfo());
1092                    }
1093    
1094                    freeMarkerContext.put("validator", Validator_IW.getInstance());
1095    
1096                    String html = FreeMarkerUtil.process(_TEMPLATE_FTL, freeMarkerContext);
1097    
1098                    response.setContentType(ContentTypes.TEXT_HTML_UTF8);
1099    
1100                    ServletResponseUtil.write(response, html);
1101            }
1102    
1103            protected void writeImage(
1104                    Image image, HttpServletRequest request, HttpServletResponse response) {
1105    
1106                    if (image == null) {
1107                            return;
1108                    }
1109    
1110                    String contentType = null;
1111    
1112                    String type = image.getType();
1113    
1114                    if (!type.equals(ImageConstants.TYPE_NOT_AVAILABLE)) {
1115                            contentType = MimeTypesUtil.getContentType("A." + type);
1116    
1117                            response.setContentType(contentType);
1118                    }
1119    
1120                    String fileName = ParamUtil.getString(request, "fileName");
1121    
1122                    try {
1123                            byte[] bytes = getImageBytes(request, image);
1124    
1125                            if (Validator.isNotNull(fileName)) {
1126                                    ServletResponseUtil.sendFile(
1127                                            request, response, fileName, bytes, contentType);
1128                            }
1129                            else {
1130                                    ServletResponseUtil.write(response, bytes);
1131                            }
1132                    }
1133                    catch (Exception e) {
1134                            if (_log.isWarnEnabled()) {
1135                                    _log.warn(e, e);
1136                            }
1137                    }
1138            }
1139    
1140            private static void _checkDDMRecord(String[] pathArray) throws Exception {
1141                    if (pathArray.length == 3) {
1142                            String className = GetterUtil.getString(pathArray[1]);
1143                            long classPK = GetterUtil.getLong(pathArray[2]);
1144    
1145                            if (className.equals(DDLRecord.class.getName())) {
1146                                    DDLRecordLocalServiceUtil.getRecord(classPK);
1147                            }
1148                            else if (className.equals(DLFileEntryMetadata.class.getName())) {
1149                                    DLFileEntryMetadataLocalServiceUtil.getDLFileEntryMetadata(
1150                                            classPK);
1151                            }
1152                    }
1153            }
1154    
1155            private static void _checkFileEntry(String[] pathArray) throws Exception {
1156                    if (pathArray.length == 1) {
1157                            long dlFileShortcutId = GetterUtil.getLong(pathArray[0]);
1158    
1159                            DLFileShortcut dlFileShortcut =
1160                                    DLAppLocalServiceUtil.getFileShortcut(dlFileShortcutId);
1161    
1162                            DLAppLocalServiceUtil.getFileEntry(
1163                                    dlFileShortcut.getToFileEntryId());
1164                    }
1165                    else if (pathArray.length == 2) {
1166    
1167                            // Unable to check with UUID because of multiple repositories
1168    
1169                    }
1170                    else if (pathArray.length == 3) {
1171                            long groupId = GetterUtil.getLong(pathArray[0]);
1172                            long folderId = GetterUtil.getLong(pathArray[1]);
1173                            String fileName = HttpUtil.decodeURL(pathArray[2]);
1174    
1175                            try {
1176                                    DLAppLocalServiceUtil.getFileEntry(groupId, folderId, fileName);
1177                            }
1178                            catch (RepositoryException re) {
1179                            }
1180                    }
1181                    else {
1182                            long groupId = GetterUtil.getLong(pathArray[0]);
1183    
1184                            String uuid = pathArray[3];
1185    
1186                            try {
1187                                    DLAppLocalServiceUtil.getFileEntryByUuidAndGroupId(
1188                                            uuid, groupId);
1189                            }
1190                            catch (RepositoryException re) {
1191                            }
1192                    }
1193            }
1194    
1195            private static long _getGroupId(long companyId, String name)
1196                    throws Exception {
1197    
1198                    try {
1199                            Group group = GroupLocalServiceUtil.getFriendlyURLGroup(
1200                                    companyId, StringPool.SLASH + name);
1201    
1202                            return group.getGroupId();
1203                    }
1204                    catch (NoSuchGroupException nsge) {
1205                    }
1206    
1207                    User user = UserLocalServiceUtil.getUserByScreenName(companyId, name);
1208    
1209                    Group group = user.getGroup();
1210    
1211                    return group.getGroupId();
1212            }
1213    
1214            private static User _getUser(HttpServletRequest request) throws Exception {
1215                    HttpSession session = request.getSession();
1216    
1217                    if (PortalSessionThreadLocal.getHttpSession() == null) {
1218                            PortalSessionThreadLocal.setHttpSession(session);
1219                    }
1220    
1221                    User user = PortalUtil.getUser(request);
1222    
1223                    if (user != null) {
1224                            return user;
1225                    }
1226    
1227                    String userIdString = (String)session.getAttribute("j_username");
1228                    String password = (String)session.getAttribute("j_password");
1229    
1230                    if ((userIdString != null) && (password != null)) {
1231                            long userId = GetterUtil.getLong(userIdString);
1232    
1233                            user = UserLocalServiceUtil.getUser(userId);
1234                    }
1235                    else {
1236                            long companyId = PortalUtil.getCompanyId(request);
1237    
1238                            Company company = CompanyLocalServiceUtil.getCompany(companyId);
1239    
1240                            user = company.getDefaultUser();
1241                    }
1242    
1243                    return user;
1244            }
1245    
1246            private static final String _DATE_FORMAT_PATTERN = "d MMM yyyy HH:mm z";
1247    
1248            private static final String _PATH_DDM = "ddm";
1249    
1250            private static final String _TEMPLATE_FTL =
1251                    "com/liferay/portal/webserver/dependencies/template.ftl";
1252    
1253            private static final boolean _WEB_SERVER_SERVLET_VERSION_VERBOSITY_DEFAULT =
1254                    PropsValues.WEB_SERVER_SERVLET_VERSION_VERBOSITY.equalsIgnoreCase(
1255                            ReleaseInfo.getName());
1256    
1257            private static final boolean _WEB_SERVER_SERVLET_VERSION_VERBOSITY_PARTIAL =
1258                    PropsValues.WEB_SERVER_SERVLET_VERSION_VERBOSITY.equalsIgnoreCase(
1259                            "partial");
1260    
1261            private static Log _log = LogFactoryUtil.getLog(WebServerServlet.class);
1262    
1263            private static Set<String> _acceptRangesMimeTypes = SetUtil.fromArray(
1264                    PropsValues.WEB_SERVER_SERVLET_ACCEPT_RANGES_MIME_TYPES);
1265    
1266            private static Format _dateFormat =
1267                    FastDateFormatFactoryUtil.getSimpleDateFormat(_DATE_FORMAT_PATTERN);
1268    
1269            private boolean _lastModified = true;
1270    
1271    }