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