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