001    /**
002     * Copyright (c) 2000-present Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portlet.admin.action;
016    
017    import com.liferay.mail.service.MailServiceUtil;
018    import com.liferay.portal.captcha.CaptchaImpl;
019    import com.liferay.portal.captcha.recaptcha.ReCaptchaImpl;
020    import com.liferay.portal.captcha.simplecaptcha.SimpleCaptchaImpl;
021    import com.liferay.portal.convert.ConvertException;
022    import com.liferay.portal.convert.ConvertProcess;
023    import com.liferay.portal.kernel.cache.CacheRegistryUtil;
024    import com.liferay.portal.kernel.cache.MultiVMPoolUtil;
025    import com.liferay.portal.kernel.cache.SingleVMPoolUtil;
026    import com.liferay.portal.kernel.captcha.Captcha;
027    import com.liferay.portal.kernel.captcha.CaptchaUtil;
028    import com.liferay.portal.kernel.cluster.Address;
029    import com.liferay.portal.kernel.cluster.ClusterExecutorUtil;
030    import com.liferay.portal.kernel.cluster.ClusterLink;
031    import com.liferay.portal.kernel.cluster.ClusterRequest;
032    import com.liferay.portal.kernel.concurrent.ThreadPoolExecutor;
033    import com.liferay.portal.kernel.dao.shard.ShardUtil;
034    import com.liferay.portal.kernel.exception.SystemException;
035    import com.liferay.portal.kernel.executor.PortalExecutorManagerUtil;
036    import com.liferay.portal.kernel.image.GhostscriptUtil;
037    import com.liferay.portal.kernel.image.ImageMagickUtil;
038    import com.liferay.portal.kernel.io.unsync.UnsyncByteArrayOutputStream;
039    import com.liferay.portal.kernel.io.unsync.UnsyncPrintWriter;
040    import com.liferay.portal.kernel.json.JSONFactoryUtil;
041    import com.liferay.portal.kernel.json.JSONObject;
042    import com.liferay.portal.kernel.log.Log;
043    import com.liferay.portal.kernel.log.LogFactoryUtil;
044    import com.liferay.portal.kernel.log.SanitizerLogWrapper;
045    import com.liferay.portal.kernel.mail.Account;
046    import com.liferay.portal.kernel.messaging.BaseAsyncDestination;
047    import com.liferay.portal.kernel.messaging.Destination;
048    import com.liferay.portal.kernel.messaging.DestinationNames;
049    import com.liferay.portal.kernel.messaging.MessageBus;
050    import com.liferay.portal.kernel.messaging.MessageBusUtil;
051    import com.liferay.portal.kernel.messaging.proxy.MessageValuesThreadLocal;
052    import com.liferay.portal.kernel.scripting.ScriptingException;
053    import com.liferay.portal.kernel.scripting.ScriptingHelperUtil;
054    import com.liferay.portal.kernel.scripting.ScriptingUtil;
055    import com.liferay.portal.kernel.search.Indexer;
056    import com.liferay.portal.kernel.search.SearchEngineUtil;
057    import com.liferay.portal.kernel.servlet.DirectServletRegistryUtil;
058    import com.liferay.portal.kernel.servlet.SessionErrors;
059    import com.liferay.portal.kernel.servlet.SessionMessages;
060    import com.liferay.portal.kernel.util.CharPool;
061    import com.liferay.portal.kernel.util.Constants;
062    import com.liferay.portal.kernel.util.InstancePool;
063    import com.liferay.portal.kernel.util.MethodHandler;
064    import com.liferay.portal.kernel.util.MethodKey;
065    import com.liferay.portal.kernel.util.ParamUtil;
066    import com.liferay.portal.kernel.util.ProgressStatusConstants;
067    import com.liferay.portal.kernel.util.ProgressTracker;
068    import com.liferay.portal.kernel.util.PropsKeys;
069    import com.liferay.portal.kernel.util.StringBundler;
070    import com.liferay.portal.kernel.util.StringPool;
071    import com.liferay.portal.kernel.util.StringUtil;
072    import com.liferay.portal.kernel.util.ThreadUtil;
073    import com.liferay.portal.kernel.util.Time;
074    import com.liferay.portal.kernel.util.UnsyncPrintWriterPool;
075    import com.liferay.portal.kernel.util.Validator;
076    import com.liferay.portal.kernel.xuggler.XugglerUtil;
077    import com.liferay.portal.model.Portlet;
078    import com.liferay.portal.search.SearchEngineInitializer;
079    import com.liferay.portal.search.lucene.LuceneHelperUtil;
080    import com.liferay.portal.search.lucene.cluster.LuceneClusterUtil;
081    import com.liferay.portal.security.auth.PrincipalException;
082    import com.liferay.portal.security.lang.DoPrivilegedBean;
083    import com.liferay.portal.security.membershippolicy.OrganizationMembershipPolicy;
084    import com.liferay.portal.security.membershippolicy.OrganizationMembershipPolicyFactoryUtil;
085    import com.liferay.portal.security.membershippolicy.RoleMembershipPolicy;
086    import com.liferay.portal.security.membershippolicy.RoleMembershipPolicyFactoryUtil;
087    import com.liferay.portal.security.membershippolicy.SiteMembershipPolicy;
088    import com.liferay.portal.security.membershippolicy.SiteMembershipPolicyFactoryUtil;
089    import com.liferay.portal.security.membershippolicy.UserGroupMembershipPolicy;
090    import com.liferay.portal.security.membershippolicy.UserGroupMembershipPolicyFactoryUtil;
091    import com.liferay.portal.security.permission.PermissionChecker;
092    import com.liferay.portal.service.PortletLocalServiceUtil;
093    import com.liferay.portal.service.ServiceComponentLocalServiceUtil;
094    import com.liferay.portal.struts.ActionConstants;
095    import com.liferay.portal.struts.PortletAction;
096    import com.liferay.portal.theme.ThemeDisplay;
097    import com.liferay.portal.upload.UploadServletRequestImpl;
098    import com.liferay.portal.util.MaintenanceUtil;
099    import com.liferay.portal.util.Portal;
100    import com.liferay.portal.util.PortalInstances;
101    import com.liferay.portal.util.PrefsPropsUtil;
102    import com.liferay.portal.util.PropsValues;
103    import com.liferay.portal.util.ShutdownUtil;
104    import com.liferay.portal.util.WebKeys;
105    import com.liferay.portlet.ActionResponseImpl;
106    import com.liferay.portlet.admin.util.CleanUpPermissionsUtil;
107    import com.liferay.portlet.documentlibrary.util.DLPreviewableProcessor;
108    import com.liferay.util.log4j.Log4JUtil;
109    
110    import java.io.File;
111    
112    import java.util.Enumeration;
113    import java.util.HashSet;
114    import java.util.List;
115    import java.util.Map;
116    import java.util.Set;
117    import java.util.concurrent.CountDownLatch;
118    import java.util.concurrent.TimeUnit;
119    
120    import javax.portlet.ActionRequest;
121    import javax.portlet.ActionResponse;
122    import javax.portlet.PortletConfig;
123    import javax.portlet.PortletContext;
124    import javax.portlet.PortletPreferences;
125    import javax.portlet.PortletSession;
126    import javax.portlet.PortletURL;
127    import javax.portlet.WindowState;
128    
129    import org.apache.log4j.Level;
130    import org.apache.struts.action.ActionForm;
131    import org.apache.struts.action.ActionMapping;
132    
133    /**
134     * @author Brian Wing Shun Chan
135     * @author Shuyang Zhou
136     */
137    public class EditServerAction extends PortletAction {
138    
139            @Override
140            public void processAction(
141                            ActionMapping actionMapping, ActionForm actionForm,
142                            PortletConfig portletConfig, ActionRequest actionRequest,
143                            ActionResponse actionResponse)
144                    throws Exception {
145    
146                    ThemeDisplay themeDisplay = (ThemeDisplay)actionRequest.getAttribute(
147                            WebKeys.THEME_DISPLAY);
148    
149                    PermissionChecker permissionChecker =
150                            themeDisplay.getPermissionChecker();
151    
152                    if (!permissionChecker.isOmniadmin()) {
153                            SessionErrors.add(
154                                    actionRequest, PrincipalException.class.getName());
155    
156                            setForward(actionRequest, "portlet.admin.error");
157    
158                            return;
159                    }
160    
161                    PortletPreferences portletPreferences = PrefsPropsUtil.getPreferences();
162    
163                    String cmd = ParamUtil.getString(actionRequest, Constants.CMD);
164    
165                    String redirect = null;
166    
167                    if (cmd.equals("addLogLevel")) {
168                            addLogLevel(actionRequest);
169                    }
170                    else if (cmd.equals("cacheDb")) {
171                            cacheDb();
172                    }
173                    else if (cmd.equals("cacheMulti")) {
174                            cacheMulti();
175                    }
176                    else if (cmd.equals("cacheServlet")) {
177                            cacheServlet();
178                    }
179                    else if (cmd.equals("cacheSingle")) {
180                            cacheSingle();
181                    }
182                    else if (cmd.equals("cleanUpPermissions")) {
183                            CleanUpPermissionsUtil.cleanUpAddToPagePermissions(actionRequest);
184                    }
185                    else if (cmd.startsWith("convertProcess.")) {
186                            redirect = convertProcess(actionRequest, actionResponse, cmd);
187                    }
188                    else if (cmd.equals("dlPreviews")) {
189                            DLPreviewableProcessor.deleteFiles();
190                    }
191                    else if (cmd.equals("gc")) {
192                            gc();
193                    }
194                    else if (cmd.equals("installXuggler")) {
195                            installXuggler(actionRequest, actionResponse);
196    
197                            setForward(actionRequest, ActionConstants.COMMON_NULL);
198    
199                            return;
200                    }
201                    else if (cmd.equals("reindex")) {
202                            reindex(actionRequest);
203                    }
204                    else if (cmd.equals("reindexDictionaries")) {
205                            reindexDictionaries(actionRequest);
206                    }
207                    else if (cmd.equals("runScript")) {
208                            runScript(portletConfig, actionRequest, actionResponse);
209                    }
210                    else if (cmd.equals("shutdown")) {
211                            shutdown(actionRequest);
212                    }
213                    else if (cmd.equals("threadDump")) {
214                            threadDump();
215                    }
216                    else if (cmd.equals("updateCaptcha")) {
217                            updateCaptcha(actionRequest, portletPreferences);
218                    }
219                    else if (cmd.equals("updateExternalServices")) {
220                            updateExternalServices(actionRequest, portletPreferences);
221                    }
222                    else if (cmd.equals("updateFileUploads")) {
223                            updateFileUploads(actionRequest, portletPreferences);
224                    }
225                    else if (cmd.equals("updateLogLevels")) {
226                            updateLogLevels(actionRequest);
227                    }
228                    else if (cmd.equals("updateMail")) {
229                            updateMail(actionRequest, portletPreferences);
230                    }
231                    else if (cmd.equals("verifyMembershipPolicies")) {
232                            verifyMembershipPolicies();
233                    }
234                    else if (cmd.equals("verifyPluginTables")) {
235                            verifyPluginTables();
236                    }
237    
238                    sendRedirect(actionRequest, actionResponse, redirect);
239            }
240    
241            protected void addLogLevel(ActionRequest actionRequest) throws Exception {
242                    String loggerName = ParamUtil.getString(actionRequest, "loggerName");
243                    String priority = ParamUtil.getString(actionRequest, "priority");
244    
245                    Log4JUtil.setLevel(loggerName, priority, true);
246            }
247    
248            protected void cacheDb() throws Exception {
249                    CacheRegistryUtil.clear();
250            }
251    
252            protected void cacheMulti() throws Exception {
253                    MultiVMPoolUtil.clear();
254            }
255    
256            protected void cacheServlet() throws Exception {
257                    DirectServletRegistryUtil.clearServlets();
258            }
259    
260            protected void cacheSingle() throws Exception {
261                    SingleVMPoolUtil.clear();
262            }
263    
264            protected String convertProcess(
265                            ActionRequest actionRequest, ActionResponse actionResponse,
266                            String cmd)
267                    throws Exception {
268    
269                    ActionResponseImpl actionResponseImpl =
270                            (ActionResponseImpl)actionResponse;
271    
272                    PortletSession portletSession = actionRequest.getPortletSession();
273    
274                    String className = StringUtil.replaceFirst(
275                            cmd, "convertProcess.", StringPool.BLANK);
276    
277                    ConvertProcess convertProcess = (ConvertProcess)InstancePool.get(
278                            className);
279    
280                    String[] parameters = convertProcess.getParameterNames();
281    
282                    if (parameters != null) {
283                            String[] values = new String[parameters.length];
284    
285                            for (int i = 0; i < parameters.length; i++) {
286                                    String parameter =
287                                            className + StringPool.PERIOD + parameters[i];
288    
289                                    if (parameters[i].contains(StringPool.EQUAL)) {
290                                            String[] parameterPair = StringUtil.split(
291                                                    parameters[i], CharPool.EQUAL);
292    
293                                            parameter =
294                                                    className + StringPool.PERIOD + parameterPair[0];
295                                    }
296    
297                                    values[i] = ParamUtil.getString(actionRequest, parameter);
298                            }
299    
300                            convertProcess.setParameterValues(values);
301                    }
302    
303                    try {
304                            convertProcess.validate();
305                    }
306                    catch (ConvertException ce) {
307                            SessionErrors.add(actionRequest, ce.getClass(), ce);
308    
309                            return null;
310                    }
311    
312                    String path = convertProcess.getPath();
313    
314                    if (path != null) {
315                            PortletURL portletURL = actionResponseImpl.createRenderURL();
316    
317                            portletURL.setParameter("struts_action", path);
318                            portletURL.setWindowState(WindowState.MAXIMIZED);
319    
320                            return portletURL.toString();
321                    }
322    
323                    MaintenanceUtil.maintain(portletSession.getId(), className);
324    
325                    MessageBusUtil.sendMessage(DestinationNames.CONVERT_PROCESS, className);
326    
327                    return null;
328            }
329    
330            protected void gc() throws Exception {
331                    Runtime.getRuntime().gc();
332            }
333    
334            protected String getFileExtensions(
335                    ActionRequest actionRequest, String name) {
336    
337                    String value = ParamUtil.getString(actionRequest, name);
338    
339                    return value.replace(", .", ",.");
340            }
341    
342            protected void installXuggler(
343                            ActionRequest actionRequest, ActionResponse actionResponse)
344                    throws Exception {
345    
346                    ProgressTracker progressTracker = new ProgressTracker(
347                            WebKeys.XUGGLER_INSTALL_STATUS);
348    
349                    progressTracker.addProgress(
350                            ProgressStatusConstants.DOWNLOADING, 15, "downloading-xuggler");
351                    progressTracker.addProgress(
352                            ProgressStatusConstants.COPYING, 70, "copying-xuggler-files");
353    
354                    progressTracker.initialize(actionRequest);
355    
356                    String jarName = ParamUtil.getString(actionRequest, "jarName");
357    
358                    try {
359                            XugglerUtil.installNativeLibraries(jarName, progressTracker);
360    
361                            JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
362    
363                            jsonObject.put("success", Boolean.TRUE);
364    
365                            writeJSON(actionRequest, actionResponse, jsonObject);
366                    }
367                    catch (Exception e) {
368                            JSONObject jsonObject = JSONFactoryUtil.createJSONObject();
369    
370                            jsonObject.put("exception", e.getMessage());
371                            jsonObject.put("success", Boolean.FALSE);
372    
373                            writeJSON(actionRequest, actionResponse, jsonObject);
374                    }
375    
376                    progressTracker.finish(actionRequest);
377            }
378    
379            protected void reindex(ActionRequest actionRequest) throws Exception {
380                    String portletId = ParamUtil.getString(actionRequest, "portletId");
381    
382                    long[] companyIds = PortalInstances.getCompanyIds();
383    
384                    if (LuceneHelperUtil.isLoadIndexFromClusterEnabled()) {
385                            MessageValuesThreadLocal.setValue(
386                                    ClusterLink.CLUSTER_FORWARD_MESSAGE, true);
387                    }
388    
389                    Set<String> usedSearchEngineIds = new HashSet<String>();
390    
391                    if (Validator.isNull(portletId)) {
392                            for (long companyId : companyIds) {
393                                    try {
394                                            SearchEngineInitializer searchEngineInitializer =
395                                                    new SearchEngineInitializer(companyId);
396    
397                                            searchEngineInitializer.reindex();
398    
399                                            usedSearchEngineIds.addAll(
400                                                    searchEngineInitializer.getUsedSearchEngineIds());
401                                    }
402                                    catch (Exception e) {
403                                            _log.error(e, e);
404                                    }
405                            }
406                    }
407                    else {
408                            Portlet portlet = PortletLocalServiceUtil.getPortletById(
409                                    companyIds[0], portletId);
410    
411                            if (portlet == null) {
412                                    return;
413                            }
414    
415                            List<Indexer> indexers = portlet.getIndexerInstances();
416    
417                            if (indexers == null) {
418                                    return;
419                            }
420    
421                            Set<String> searchEngineIds = new HashSet<String>();
422    
423                            for (Indexer indexer : indexers) {
424                                    searchEngineIds.add(indexer.getSearchEngineId());
425                            }
426    
427                            for (String searchEngineId : searchEngineIds) {
428                                    for (long companyId : companyIds) {
429                                            SearchEngineUtil.deletePortletDocuments(
430                                                    searchEngineId, companyId, portletId, true);
431                                    }
432                            }
433    
434                            for (Indexer indexer : indexers) {
435                                    for (long companyId : companyIds) {
436                                            ShardUtil.pushCompanyService(companyId);
437    
438                                            try {
439                                                    indexer.reindex(
440                                                            new String[] {String.valueOf(companyId)});
441    
442                                                    usedSearchEngineIds.add(indexer.getSearchEngineId());
443                                            }
444                                            catch (Exception e) {
445                                                    _log.error(e, e);
446                                            }
447                                            finally {
448                                                    ShardUtil.popCompanyService();
449                                            }
450                                    }
451                            }
452                    }
453    
454                    if (!LuceneHelperUtil.isLoadIndexFromClusterEnabled()) {
455                            return;
456                    }
457    
458                    Set<BaseAsyncDestination> searchWriterDestinations =
459                            new HashSet<BaseAsyncDestination>();
460    
461                    MessageBus messageBus = MessageBusUtil.getMessageBus();
462    
463                    for (String usedSearchEngineId : usedSearchEngineIds) {
464                            String searchWriterDestinationName =
465                                    SearchEngineUtil.getSearchWriterDestinationName(
466                                            usedSearchEngineId);
467    
468                            Destination destination = messageBus.getDestination(
469                                    searchWriterDestinationName);
470    
471                            if (destination instanceof BaseAsyncDestination) {
472                                    BaseAsyncDestination baseAsyncDestination =
473                                            (BaseAsyncDestination)destination;
474    
475                                    searchWriterDestinations.add(baseAsyncDestination);
476                            }
477                    }
478    
479                    submitClusterIndexLoadingSyncJob(searchWriterDestinations, companyIds);
480            }
481    
482            protected void reindexDictionaries(ActionRequest actionRequest)
483                    throws Exception {
484    
485                    long[] companyIds = PortalInstances.getCompanyIds();
486    
487                    for (long companyId : companyIds) {
488                            SearchEngineUtil.indexQuerySuggestionDictionaries(companyId);
489                            SearchEngineUtil.indexSpellCheckerDictionaries(companyId);
490                    }
491            }
492    
493            protected void runScript(
494                            PortletConfig portletConfig, ActionRequest actionRequest,
495                            ActionResponse actionResponse)
496                    throws Exception {
497    
498                    String language = ParamUtil.getString(actionRequest, "language");
499                    String script = ParamUtil.getString(actionRequest, "script");
500    
501                    PortletContext portletContext = portletConfig.getPortletContext();
502    
503                    Map<String, Object> portletObjects =
504                            ScriptingHelperUtil.getPortletObjects(
505                                    portletConfig, portletContext, actionRequest, actionResponse);
506    
507                    UnsyncByteArrayOutputStream unsyncByteArrayOutputStream =
508                            new UnsyncByteArrayOutputStream();
509    
510                    UnsyncPrintWriter unsyncPrintWriter = UnsyncPrintWriterPool.borrow(
511                            unsyncByteArrayOutputStream);
512    
513                    portletObjects.put("out", unsyncPrintWriter);
514    
515                    try {
516                            SessionMessages.add(actionRequest, "language", language);
517                            SessionMessages.add(actionRequest, "script", script);
518    
519                            ScriptingUtil.exec(
520                                    null, portletObjects, language, script, StringPool.EMPTY_ARRAY);
521    
522                            unsyncPrintWriter.flush();
523    
524                            SessionMessages.add(
525                                    actionRequest, "scriptOutput",
526                                    unsyncByteArrayOutputStream.toString());
527                    }
528                    catch (ScriptingException se) {
529                            SessionErrors.add(
530                                    actionRequest, ScriptingException.class.getName(), se);
531    
532                            Log log = SanitizerLogWrapper.allowCRLF(_log);
533    
534                            log.error(se.getMessage());
535                    }
536            }
537    
538            protected void shutdown(ActionRequest actionRequest) throws Exception {
539                    if (ShutdownUtil.isInProcess()) {
540                            ShutdownUtil.cancel();
541                    }
542                    else {
543                            long minutes =
544                                    ParamUtil.getInteger(actionRequest, "minutes") * Time.MINUTE;
545    
546                            if (minutes <= 0) {
547                                    SessionErrors.add(actionRequest, "shutdownMinutes");
548                            }
549                            else {
550                                    String message = ParamUtil.getString(actionRequest, "message");
551    
552                                    ShutdownUtil.shutdown(minutes, message);
553                            }
554                    }
555            }
556    
557            protected void submitClusterIndexLoadingSyncJob(
558                            Set<BaseAsyncDestination> baseAsyncDestinations, long[] companyIds)
559                    throws Exception {
560    
561                    if (_log.isInfoEnabled()) {
562                            StringBundler sb = new StringBundler(
563                                    baseAsyncDestinations.size() + 1);
564    
565                            sb.append("[");
566    
567                            for (BaseAsyncDestination baseAsyncDestination :
568                                            baseAsyncDestinations) {
569    
570                                    sb.append(baseAsyncDestination.getName());
571                                    sb.append(", ");
572                            }
573    
574                            sb.setStringAt("]", sb.index() - 1);
575    
576                            _log.info(
577                                    "Synchronizecluster index loading for destinations " +
578                                            sb.toString());
579                    }
580    
581                    int totalWorkersMaxSize = 0;
582    
583                    for (BaseAsyncDestination baseAsyncDestination :
584                                    baseAsyncDestinations) {
585    
586                            totalWorkersMaxSize += baseAsyncDestination.getWorkersMaxSize();
587                    }
588    
589                    if (_log.isInfoEnabled()) {
590                            _log.info(
591                                    "There are " + totalWorkersMaxSize +
592                                            " synchronization threads");
593                    }
594    
595                    CountDownLatch countDownLatch = new CountDownLatch(
596                            totalWorkersMaxSize + 1);
597    
598                    ClusterLoadingSyncJob slaveClusterLoadingSyncJob =
599                            new ClusterLoadingSyncJob(companyIds, countDownLatch, false);
600    
601                    for (BaseAsyncDestination baseAsyncDestination :
602                                    baseAsyncDestinations) {
603    
604                            ThreadPoolExecutor threadPoolExecutor =
605                                    PortalExecutorManagerUtil.getPortalExecutor(
606                                            baseAsyncDestination.getName());
607    
608                            for (int i = 0; i < baseAsyncDestination.getWorkersMaxSize(); i++) {
609                                    threadPoolExecutor.execute(slaveClusterLoadingSyncJob);
610                            }
611                    }
612    
613                    ClusterLoadingSyncJob masterClusterLoadingSyncJob =
614                            new ClusterLoadingSyncJob(companyIds, countDownLatch, true);
615    
616                    ThreadPoolExecutor threadPoolExecutor =
617                            PortalExecutorManagerUtil.getPortalExecutor(
618                                    EditServerAction.class.getName());
619    
620                    threadPoolExecutor.execute(masterClusterLoadingSyncJob);
621            }
622    
623            protected void threadDump() throws Exception {
624                    if (_log.isInfoEnabled()) {
625                            Log log = SanitizerLogWrapper.allowCRLF(_log);
626    
627                            log.info(ThreadUtil.threadDump());
628                    }
629                    else {
630                            _log.error(
631                                    "Thread dumps require the log level to be at least INFO for " +
632                                            getClass().getName());
633                    }
634            }
635    
636            protected void updateCaptcha(
637                            ActionRequest actionRequest, PortletPreferences portletPreferences)
638                    throws Exception {
639    
640                    boolean reCaptchaEnabled = ParamUtil.getBoolean(
641                            actionRequest, "reCaptchaEnabled");
642                    String reCaptchaPrivateKey = ParamUtil.getString(
643                            actionRequest, "reCaptchaPrivateKey");
644                    String reCaptchaPublicKey = ParamUtil.getString(
645                            actionRequest, "reCaptchaPublicKey");
646    
647                    Captcha captcha = null;
648    
649                    if (reCaptchaEnabled) {
650                            captcha = new ReCaptchaImpl();
651                    }
652                    else {
653                            captcha = new SimpleCaptchaImpl();
654                    }
655    
656                    validateCaptcha(actionRequest);
657    
658                    if (SessionErrors.isEmpty(actionRequest)) {
659                            portletPreferences.setValue(
660                                    PropsKeys.CAPTCHA_ENGINE_IMPL, captcha.getClass().getName());
661                            portletPreferences.setValue(
662                                    PropsKeys.CAPTCHA_ENGINE_RECAPTCHA_KEY_PRIVATE,
663                                    reCaptchaPrivateKey);
664                            portletPreferences.setValue(
665                                    PropsKeys.CAPTCHA_ENGINE_RECAPTCHA_KEY_PUBLIC,
666                                    reCaptchaPublicKey);
667    
668                            portletPreferences.store();
669    
670                            CaptchaImpl captchaImpl = null;
671    
672                            Captcha currentCaptcha = CaptchaUtil.getCaptcha();
673    
674                            if (currentCaptcha instanceof DoPrivilegedBean) {
675                                    DoPrivilegedBean doPrivilegedBean =
676                                            (DoPrivilegedBean)currentCaptcha;
677    
678                                    captchaImpl = (CaptchaImpl)doPrivilegedBean.getActualBean();
679                            }
680                            else {
681                                    captchaImpl = (CaptchaImpl)currentCaptcha;
682                            }
683    
684                            captchaImpl.setCaptcha(captcha);
685                    }
686            }
687    
688            protected void updateExternalServices(
689                            ActionRequest actionRequest, PortletPreferences portletPreferences)
690                    throws Exception {
691    
692                    boolean imageMagickEnabled = ParamUtil.getBoolean(
693                            actionRequest, "imageMagickEnabled");
694                    String imageMagickPath = ParamUtil.getString(
695                            actionRequest, "imageMagickPath");
696                    boolean openOfficeEnabled = ParamUtil.getBoolean(
697                            actionRequest, "openOfficeEnabled");
698                    int openOfficePort = ParamUtil.getInteger(
699                            actionRequest, "openOfficePort");
700                    boolean xugglerEnabled = ParamUtil.getBoolean(
701                            actionRequest, "xugglerEnabled");
702    
703                    portletPreferences.setValue(
704                            PropsKeys.IMAGEMAGICK_ENABLED, String.valueOf(imageMagickEnabled));
705                    portletPreferences.setValue(
706                            PropsKeys.IMAGEMAGICK_GLOBAL_SEARCH_PATH, imageMagickPath);
707                    portletPreferences.setValue(
708                            PropsKeys.OPENOFFICE_SERVER_ENABLED,
709                            String.valueOf(openOfficeEnabled));
710                    portletPreferences.setValue(
711                            PropsKeys.OPENOFFICE_SERVER_PORT, String.valueOf(openOfficePort));
712                    portletPreferences.setValue(
713                            PropsKeys.XUGGLER_ENABLED, String.valueOf(xugglerEnabled));
714    
715                    Enumeration<String> enu = actionRequest.getParameterNames();
716    
717                    while (enu.hasMoreElements()) {
718                            String name = enu.nextElement();
719    
720                            if (name.startsWith("imageMagickLimit")) {
721                                    String key = StringUtil.toLowerCase(
722                                            name.substring(16, name.length()));
723                                    String value = ParamUtil.getString(actionRequest, name);
724    
725                                    portletPreferences.setValue(
726                                            PropsKeys.IMAGEMAGICK_RESOURCE_LIMIT + key, value);
727                            }
728                    }
729    
730                    portletPreferences.store();
731    
732                    GhostscriptUtil.reset();
733                    ImageMagickUtil.reset();
734            }
735    
736            protected void updateFileUploads(
737                            ActionRequest actionRequest, PortletPreferences portletPreferences)
738                    throws Exception {
739    
740                    long dlFileEntryPreviewableProcessorMaxSize = ParamUtil.getLong(
741                            actionRequest, "dlFileEntryPreviewableProcessorMaxSize");
742                    long dlFileEntryThumbnailMaxHeight = ParamUtil.getLong(
743                            actionRequest, "dlFileEntryThumbnailMaxHeight");
744                    long dlFileEntryThumbnailMaxWidth = ParamUtil.getLong(
745                            actionRequest, "dlFileEntryThumbnailMaxWidth");
746                    String dlFileExtensions = getFileExtensions(
747                            actionRequest, "dlFileExtensions");
748                    long dlFileMaxSize = ParamUtil.getLong(actionRequest, "dlFileMaxSize");
749                    String journalImageExtensions = getFileExtensions(
750                            actionRequest, "journalImageExtensions");
751                    long journalImageSmallMaxSize = ParamUtil.getLong(
752                            actionRequest, "journalImageSmallMaxSize");
753                    String shoppingImageExtensions = getFileExtensions(
754                            actionRequest, "shoppingImageExtensions");
755                    long scImageMaxSize = ParamUtil.getLong(
756                            actionRequest, "scImageMaxSize");
757                    long scImageThumbnailMaxHeight = ParamUtil.getLong(
758                            actionRequest, "scImageThumbnailMaxHeight");
759                    long scImageThumbnailMaxWidth = ParamUtil.getLong(
760                            actionRequest, "scImageThumbnailMaxWidth");
761                    long shoppingImageLargeMaxSize = ParamUtil.getLong(
762                            actionRequest, "shoppingImageLargeMaxSize");
763                    long shoppingImageMediumMaxSize = ParamUtil.getLong(
764                            actionRequest, "shoppingImageMediumMaxSize");
765                    long shoppingImageSmallMaxSize = ParamUtil.getLong(
766                            actionRequest, "shoppingImageSmallMaxSize");
767                    long uploadServletRequestImplMaxSize = ParamUtil.getLong(
768                            actionRequest, "uploadServletRequestImplMaxSize");
769                    String uploadServletRequestImplTempDir = ParamUtil.getString(
770                            actionRequest, "uploadServletRequestImplTempDir");
771                    long usersImageMaxSize = ParamUtil.getLong(
772                            actionRequest, "usersImageMaxSize");
773    
774                    portletPreferences.setValue(
775                            PropsKeys.DL_FILE_ENTRY_PREVIEWABLE_PROCESSOR_MAX_SIZE,
776                            String.valueOf(dlFileEntryPreviewableProcessorMaxSize));
777                    portletPreferences.setValue(
778                            PropsKeys.DL_FILE_ENTRY_THUMBNAIL_MAX_HEIGHT,
779                            String.valueOf(dlFileEntryThumbnailMaxHeight));
780                    portletPreferences.setValue(
781                            PropsKeys.DL_FILE_ENTRY_THUMBNAIL_MAX_WIDTH,
782                            String.valueOf(dlFileEntryThumbnailMaxWidth));
783                    portletPreferences.setValue(
784                            PropsKeys.DL_FILE_EXTENSIONS, dlFileExtensions);
785                    portletPreferences.setValue(
786                            PropsKeys.DL_FILE_MAX_SIZE, String.valueOf(dlFileMaxSize));
787                    portletPreferences.setValue(
788                            PropsKeys.JOURNAL_IMAGE_EXTENSIONS, journalImageExtensions);
789                    portletPreferences.setValue(
790                            PropsKeys.JOURNAL_IMAGE_SMALL_MAX_SIZE,
791                            String.valueOf(journalImageSmallMaxSize));
792                    portletPreferences.setValue(
793                            PropsKeys.SHOPPING_IMAGE_EXTENSIONS, shoppingImageExtensions);
794                    portletPreferences.setValue(
795                            PropsKeys.SHOPPING_IMAGE_LARGE_MAX_SIZE,
796                            String.valueOf(shoppingImageLargeMaxSize));
797                    portletPreferences.setValue(
798                            PropsKeys.SHOPPING_IMAGE_MEDIUM_MAX_SIZE,
799                            String.valueOf(shoppingImageMediumMaxSize));
800                    portletPreferences.setValue(
801                            PropsKeys.SHOPPING_IMAGE_SMALL_MAX_SIZE,
802                            String.valueOf(shoppingImageSmallMaxSize));
803                    portletPreferences.setValue(
804                            PropsKeys.SC_IMAGE_MAX_SIZE, String.valueOf(scImageMaxSize));
805                    portletPreferences.setValue(
806                            PropsKeys.SC_IMAGE_THUMBNAIL_MAX_HEIGHT,
807                            String.valueOf(scImageThumbnailMaxHeight));
808                    portletPreferences.setValue(
809                            PropsKeys.SC_IMAGE_THUMBNAIL_MAX_WIDTH,
810                            String.valueOf(scImageThumbnailMaxWidth));
811                    portletPreferences.setValue(
812                            PropsKeys.UPLOAD_SERVLET_REQUEST_IMPL_MAX_SIZE,
813                            String.valueOf(uploadServletRequestImplMaxSize));
814    
815                    if (Validator.isNotNull(uploadServletRequestImplTempDir)) {
816                            portletPreferences.setValue(
817                                    PropsKeys.UPLOAD_SERVLET_REQUEST_IMPL_TEMP_DIR,
818                                    uploadServletRequestImplTempDir);
819    
820                            UploadServletRequestImpl.setTempDir(
821                                    new File(uploadServletRequestImplTempDir));
822                    }
823    
824                    portletPreferences.setValue(
825                            PropsKeys.USERS_IMAGE_MAX_SIZE, String.valueOf(usersImageMaxSize));
826    
827                    portletPreferences.store();
828            }
829    
830            protected void updateLogLevels(ActionRequest actionRequest)
831                    throws Exception {
832    
833                    Enumeration<String> enu = actionRequest.getParameterNames();
834    
835                    while (enu.hasMoreElements()) {
836                            String name = enu.nextElement();
837    
838                            if (name.startsWith("logLevel")) {
839                                    String loggerName = name.substring(8);
840    
841                                    String priority = ParamUtil.getString(
842                                            actionRequest, name, Level.INFO.toString());
843    
844                                    Log4JUtil.setLevel(loggerName, priority, true);
845                            }
846                    }
847            }
848    
849            protected void updateMail(
850                            ActionRequest actionRequest, PortletPreferences portletPreferences)
851                    throws Exception {
852    
853                    String advancedProperties = ParamUtil.getString(
854                            actionRequest, "advancedProperties");
855                    String pop3Host = ParamUtil.getString(actionRequest, "pop3Host");
856                    String pop3Password = ParamUtil.getString(
857                            actionRequest, "pop3Password");
858                    int pop3Port = ParamUtil.getInteger(actionRequest, "pop3Port");
859                    boolean pop3Secure = ParamUtil.getBoolean(actionRequest, "pop3Secure");
860                    String pop3User = ParamUtil.getString(actionRequest, "pop3User");
861                    String smtpHost = ParamUtil.getString(actionRequest, "smtpHost");
862                    String smtpPassword = ParamUtil.getString(
863                            actionRequest, "smtpPassword");
864                    int smtpPort = ParamUtil.getInteger(actionRequest, "smtpPort");
865                    boolean smtpSecure = ParamUtil.getBoolean(actionRequest, "smtpSecure");
866                    String smtpUser = ParamUtil.getString(actionRequest, "smtpUser");
867    
868                    String storeProtocol = Account.PROTOCOL_POP;
869    
870                    if (pop3Secure) {
871                            storeProtocol = Account.PROTOCOL_POPS;
872                    }
873    
874                    String transportProtocol = Account.PROTOCOL_SMTP;
875    
876                    if (smtpSecure) {
877                            transportProtocol = Account.PROTOCOL_SMTPS;
878                    }
879    
880                    portletPreferences.setValue(PropsKeys.MAIL_SESSION_MAIL, "true");
881                    portletPreferences.setValue(
882                            PropsKeys.MAIL_SESSION_MAIL_ADVANCED_PROPERTIES,
883                            advancedProperties);
884                    portletPreferences.setValue(
885                            PropsKeys.MAIL_SESSION_MAIL_POP3_HOST, pop3Host);
886    
887                    if (!pop3Password.equals(Portal.TEMP_OBFUSCATION_VALUE)) {
888                            portletPreferences.setValue(
889                                    PropsKeys.MAIL_SESSION_MAIL_POP3_PASSWORD, pop3Password);
890                    }
891    
892                    portletPreferences.setValue(
893                            PropsKeys.MAIL_SESSION_MAIL_POP3_PORT, String.valueOf(pop3Port));
894                    portletPreferences.setValue(
895                            PropsKeys.MAIL_SESSION_MAIL_POP3_USER, pop3User);
896                    portletPreferences.setValue(
897                            PropsKeys.MAIL_SESSION_MAIL_SMTP_HOST, smtpHost);
898    
899                    if (!smtpPassword.equals(Portal.TEMP_OBFUSCATION_VALUE)) {
900                            portletPreferences.setValue(
901                                    PropsKeys.MAIL_SESSION_MAIL_SMTP_PASSWORD, smtpPassword);
902                    }
903    
904                    portletPreferences.setValue(
905                            PropsKeys.MAIL_SESSION_MAIL_SMTP_PORT, String.valueOf(smtpPort));
906                    portletPreferences.setValue(
907                            PropsKeys.MAIL_SESSION_MAIL_SMTP_USER, smtpUser);
908                    portletPreferences.setValue(
909                            PropsKeys.MAIL_SESSION_MAIL_STORE_PROTOCOL, storeProtocol);
910                    portletPreferences.setValue(
911                            PropsKeys.MAIL_SESSION_MAIL_TRANSPORT_PROTOCOL, transportProtocol);
912    
913                    portletPreferences.store();
914    
915                    MailServiceUtil.clearSession();
916            }
917    
918            protected void validateCaptcha(ActionRequest actionRequest)
919                    throws Exception {
920    
921                    boolean reCaptchaEnabled = ParamUtil.getBoolean(
922                            actionRequest, "reCaptchaEnabled");
923    
924                    if (!reCaptchaEnabled) {
925                            return;
926                    }
927    
928                    String reCaptchaPrivateKey = ParamUtil.getString(
929                            actionRequest, "reCaptchaPrivateKey");
930                    String reCaptchaPublicKey = ParamUtil.getString(
931                            actionRequest, "reCaptchaPublicKey");
932    
933                    if (Validator.isNull(reCaptchaPublicKey)) {
934                            SessionErrors.add(actionRequest, "reCaptchaPublicKey");
935                    }
936                    else if (Validator.isNull(reCaptchaPrivateKey)) {
937                            SessionErrors.add(actionRequest, "reCaptchaPrivateKey");
938                    }
939            }
940    
941            protected void verifyMembershipPolicies() throws Exception {
942                    OrganizationMembershipPolicy organizationMembershipPolicy =
943                            OrganizationMembershipPolicyFactoryUtil.
944                                    getOrganizationMembershipPolicy();
945    
946                    organizationMembershipPolicy.verifyPolicy();
947    
948                    RoleMembershipPolicy roleMembershipPolicy =
949                            RoleMembershipPolicyFactoryUtil.getRoleMembershipPolicy();
950    
951                    roleMembershipPolicy.verifyPolicy();
952    
953                    SiteMembershipPolicy siteMembershipPolicy =
954                            SiteMembershipPolicyFactoryUtil.getSiteMembershipPolicy();
955    
956                    siteMembershipPolicy.verifyPolicy();
957    
958                    UserGroupMembershipPolicy userGroupMembershipPolicy =
959                            UserGroupMembershipPolicyFactoryUtil.getUserGroupMembershipPolicy();
960    
961                    userGroupMembershipPolicy.verifyPolicy();
962            }
963    
964            protected void verifyPluginTables() throws Exception {
965                    ServiceComponentLocalServiceUtil.verifyDB();
966            }
967    
968            private static Log _log = LogFactoryUtil.getLog(EditServerAction.class);
969    
970            private static MethodKey _loadIndexesFromClusterMethodKey = new MethodKey(
971                    LuceneClusterUtil.class, "loadIndexesFromCluster", long[].class,
972                    Address.class);
973    
974            private static class ClusterLoadingSyncJob implements Runnable {
975    
976                    public ClusterLoadingSyncJob(
977                            long[] companyIds, CountDownLatch countDownLatch, boolean master) {
978    
979                            _companyIds = companyIds;
980                            _countDownLatch = countDownLatch;
981                            _master = master;
982                    }
983    
984                    @Override
985                    public void run() {
986                            _countDownLatch.countDown();
987    
988                            String logPrefix = StringPool.BLANK;
989    
990                            if (_log.isInfoEnabled()) {
991                                    Thread currentThread = Thread.currentThread();
992    
993                                    if (_master) {
994                                            logPrefix =
995                                                    "Monitor thread name " + currentThread.getName() +
996                                                            " with thread ID " + currentThread.getId();
997                                    }
998                                    else {
999                                            logPrefix =
1000                                                    "Thread name " + currentThread.getName() +
1001                                                            " with thread ID " + currentThread.getId();
1002                                    }
1003                            }
1004    
1005                            if (!_master && _log.isInfoEnabled()) {
1006                                    _log.info(
1007                                            logPrefix + " synchronized on latch. Waiting for others.");
1008                            }
1009    
1010                            try {
1011                                    if (_master) {
1012                                            _countDownLatch.await();
1013                                    }
1014                                    else {
1015                                            boolean result = _countDownLatch.await(
1016                                                    PropsValues.LUCENE_CLUSTER_INDEX_LOADING_SYNC_TIMEOUT,
1017                                                    TimeUnit.MILLISECONDS);
1018    
1019                                            if (!result) {
1020                                                    _log.error(
1021                                                            logPrefix + " timed out. You may need to " +
1022                                                                    "re-trigger a reindex process.");
1023                                            }
1024                                    }
1025                            }
1026                            catch (InterruptedException ie) {
1027                                    if (_master) {
1028                                            _log.error(
1029                                                    logPrefix + " was interrupted. Skip cluster index " +
1030                                                            "loading notification.",
1031                                                    ie);
1032    
1033                                            return;
1034                                    }
1035                                    else {
1036                                            _log.error(
1037                                                    logPrefix + " was interrupted. You may need to " +
1038                                                            "re-trigger a reindex process.",
1039                                                    ie);
1040                                    }
1041                            }
1042    
1043                            if (_master) {
1044                                    Address localClusterNodeAddress =
1045                                            ClusterExecutorUtil.getLocalClusterNodeAddress();
1046    
1047                                    ClusterRequest clusterRequest =
1048                                            ClusterRequest.createMulticastRequest(
1049                                                    new MethodHandler(
1050                                                            _loadIndexesFromClusterMethodKey, _companyIds,
1051                                                            localClusterNodeAddress),
1052                                                    true);
1053    
1054                                    try {
1055                                            ClusterExecutorUtil.execute(clusterRequest);
1056                                    }
1057                                    catch (SystemException se) {
1058                                            _log.error(
1059                                                    "Unable to notify peers to start index loading", se);
1060                                    }
1061    
1062                                    if (_log.isInfoEnabled()) {
1063                                            _log.info(
1064                                                    logPrefix + " unlocked latch. Notified peers to " +
1065                                                            "start index loading.");
1066                                    }
1067                            }
1068                    }
1069    
1070                    private long[] _companyIds;
1071                    private CountDownLatch _countDownLatch;
1072                    private boolean _master;
1073    
1074            }
1075    
1076    }