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 = StringUtil.toLowerCase(
704                                            name.substring(16, name.length()));
705                                    String value = ParamUtil.getString(actionRequest, name);
706    
707                                    portletPreferences.setValue(
708                                            PropsKeys.IMAGEMAGICK_RESOURCE_LIMIT + key, value);
709                            }
710                    }
711    
712                    portletPreferences.store();
713    
714                    GhostscriptUtil.reset();
715                    ImageMagickUtil.reset();
716            }
717    
718            protected void updateFileUploads(
719                            ActionRequest actionRequest, PortletPreferences portletPreferences)
720                    throws Exception {
721    
722                    long dlFileEntryPreviewableProcessorMaxSize = ParamUtil.getLong(
723                            actionRequest, "dlFileEntryPreviewableProcessorMaxSize");
724                    long dlFileEntryThumbnailMaxHeight = ParamUtil.getLong(
725                            actionRequest, "dlFileEntryThumbnailMaxHeight");
726                    long dlFileEntryThumbnailMaxWidth = ParamUtil.getLong(
727                            actionRequest, "dlFileEntryThumbnailMaxWidth");
728                    String dlFileExtensions = getFileExtensions(
729                            actionRequest, "dlFileExtensions");
730                    long dlFileMaxSize = ParamUtil.getLong(actionRequest, "dlFileMaxSize");
731                    String journalImageExtensions = getFileExtensions(
732                            actionRequest, "journalImageExtensions");
733                    long journalImageSmallMaxSize = ParamUtil.getLong(
734                            actionRequest, "journalImageSmallMaxSize");
735                    String shoppingImageExtensions = getFileExtensions(
736                            actionRequest, "shoppingImageExtensions");
737                    long scImageMaxSize = ParamUtil.getLong(
738                            actionRequest, "scImageMaxSize");
739                    long scImageThumbnailMaxHeight = ParamUtil.getLong(
740                            actionRequest, "scImageThumbnailMaxHeight");
741                    long scImageThumbnailMaxWidth = ParamUtil.getLong(
742                            actionRequest, "scImageThumbnailMaxWidth");
743                    long shoppingImageLargeMaxSize = ParamUtil.getLong(
744                            actionRequest, "shoppingImageLargeMaxSize");
745                    long shoppingImageMediumMaxSize = ParamUtil.getLong(
746                            actionRequest, "shoppingImageMediumMaxSize");
747                    long shoppingImageSmallMaxSize = ParamUtil.getLong(
748                            actionRequest, "shoppingImageSmallMaxSize");
749                    long uploadServletRequestImplMaxSize = ParamUtil.getLong(
750                            actionRequest, "uploadServletRequestImplMaxSize");
751                    String uploadServletRequestImplTempDir = ParamUtil.getString(
752                            actionRequest, "uploadServletRequestImplTempDir");
753                    long usersImageMaxSize = ParamUtil.getLong(
754                            actionRequest, "usersImageMaxSize");
755    
756                    portletPreferences.setValue(
757                            PropsKeys.DL_FILE_ENTRY_PREVIEWABLE_PROCESSOR_MAX_SIZE,
758                            String.valueOf(dlFileEntryPreviewableProcessorMaxSize));
759                    portletPreferences.setValue(
760                            PropsKeys.DL_FILE_ENTRY_THUMBNAIL_MAX_HEIGHT,
761                            String.valueOf(dlFileEntryThumbnailMaxHeight));
762                    portletPreferences.setValue(
763                            PropsKeys.DL_FILE_ENTRY_THUMBNAIL_MAX_WIDTH,
764                            String.valueOf(dlFileEntryThumbnailMaxWidth));
765                    portletPreferences.setValue(
766                            PropsKeys.DL_FILE_EXTENSIONS, dlFileExtensions);
767                    portletPreferences.setValue(
768                            PropsKeys.DL_FILE_MAX_SIZE, String.valueOf(dlFileMaxSize));
769                    portletPreferences.setValue(
770                            PropsKeys.JOURNAL_IMAGE_EXTENSIONS, journalImageExtensions);
771                    portletPreferences.setValue(
772                            PropsKeys.JOURNAL_IMAGE_SMALL_MAX_SIZE,
773                            String.valueOf(journalImageSmallMaxSize));
774                    portletPreferences.setValue(
775                            PropsKeys.SHOPPING_IMAGE_EXTENSIONS, shoppingImageExtensions);
776                    portletPreferences.setValue(
777                            PropsKeys.SHOPPING_IMAGE_LARGE_MAX_SIZE,
778                            String.valueOf(shoppingImageLargeMaxSize));
779                    portletPreferences.setValue(
780                            PropsKeys.SHOPPING_IMAGE_MEDIUM_MAX_SIZE,
781                            String.valueOf(shoppingImageMediumMaxSize));
782                    portletPreferences.setValue(
783                            PropsKeys.SHOPPING_IMAGE_SMALL_MAX_SIZE,
784                            String.valueOf(shoppingImageSmallMaxSize));
785                    portletPreferences.setValue(
786                            PropsKeys.SC_IMAGE_MAX_SIZE, String.valueOf(scImageMaxSize));
787                    portletPreferences.setValue(
788                            PropsKeys.SC_IMAGE_THUMBNAIL_MAX_HEIGHT,
789                            String.valueOf(scImageThumbnailMaxHeight));
790                    portletPreferences.setValue(
791                            PropsKeys.SC_IMAGE_THUMBNAIL_MAX_WIDTH,
792                            String.valueOf(scImageThumbnailMaxWidth));
793                    portletPreferences.setValue(
794                            PropsKeys.UPLOAD_SERVLET_REQUEST_IMPL_MAX_SIZE,
795                            String.valueOf(uploadServletRequestImplMaxSize));
796    
797                    if (Validator.isNotNull(uploadServletRequestImplTempDir)) {
798                            portletPreferences.setValue(
799                                    PropsKeys.UPLOAD_SERVLET_REQUEST_IMPL_TEMP_DIR,
800                                    uploadServletRequestImplTempDir);
801    
802                            UploadServletRequestImpl.setTempDir(
803                                    new File(uploadServletRequestImplTempDir));
804                    }
805    
806                    portletPreferences.setValue(
807                            PropsKeys.USERS_IMAGE_MAX_SIZE, String.valueOf(usersImageMaxSize));
808    
809                    portletPreferences.store();
810            }
811    
812            protected void updateLogLevels(ActionRequest actionRequest)
813                    throws Exception {
814    
815                    Enumeration<String> enu = actionRequest.getParameterNames();
816    
817                    while (enu.hasMoreElements()) {
818                            String name = enu.nextElement();
819    
820                            if (name.startsWith("logLevel")) {
821                                    String loggerName = name.substring(8);
822    
823                                    String priority = ParamUtil.getString(
824                                            actionRequest, name, Level.INFO.toString());
825    
826                                    Log4JUtil.setLevel(loggerName, priority, true);
827                            }
828                    }
829            }
830    
831            protected void updateMail(
832                            ActionRequest actionRequest, PortletPreferences portletPreferences)
833                    throws Exception {
834    
835                    String advancedProperties = ParamUtil.getString(
836                            actionRequest, "advancedProperties");
837                    String pop3Host = ParamUtil.getString(actionRequest, "pop3Host");
838                    String pop3Password = ParamUtil.getString(
839                            actionRequest, "pop3Password");
840                    int pop3Port = ParamUtil.getInteger(actionRequest, "pop3Port");
841                    boolean pop3Secure = ParamUtil.getBoolean(actionRequest, "pop3Secure");
842                    String pop3User = ParamUtil.getString(actionRequest, "pop3User");
843                    String smtpHost = ParamUtil.getString(actionRequest, "smtpHost");
844                    String smtpPassword = ParamUtil.getString(
845                            actionRequest, "smtpPassword");
846                    int smtpPort = ParamUtil.getInteger(actionRequest, "smtpPort");
847                    boolean smtpSecure = ParamUtil.getBoolean(actionRequest, "smtpSecure");
848                    String smtpUser = ParamUtil.getString(actionRequest, "smtpUser");
849    
850                    String storeProtocol = Account.PROTOCOL_POP;
851    
852                    if (pop3Secure) {
853                            storeProtocol = Account.PROTOCOL_POPS;
854                    }
855    
856                    String transportProtocol = Account.PROTOCOL_SMTP;
857    
858                    if (smtpSecure) {
859                            transportProtocol = Account.PROTOCOL_SMTPS;
860                    }
861    
862                    portletPreferences.setValue(PropsKeys.MAIL_SESSION_MAIL, "true");
863                    portletPreferences.setValue(
864                            PropsKeys.MAIL_SESSION_MAIL_ADVANCED_PROPERTIES,
865                            advancedProperties);
866                    portletPreferences.setValue(
867                            PropsKeys.MAIL_SESSION_MAIL_POP3_HOST, pop3Host);
868                    portletPreferences.setValue(
869                            PropsKeys.MAIL_SESSION_MAIL_POP3_PASSWORD, pop3Password);
870                    portletPreferences.setValue(
871                            PropsKeys.MAIL_SESSION_MAIL_POP3_PORT, String.valueOf(pop3Port));
872                    portletPreferences.setValue(
873                            PropsKeys.MAIL_SESSION_MAIL_POP3_USER, pop3User);
874                    portletPreferences.setValue(
875                            PropsKeys.MAIL_SESSION_MAIL_SMTP_HOST, smtpHost);
876                    portletPreferences.setValue(
877                            PropsKeys.MAIL_SESSION_MAIL_SMTP_PASSWORD, smtpPassword);
878                    portletPreferences.setValue(
879                            PropsKeys.MAIL_SESSION_MAIL_SMTP_PORT, String.valueOf(smtpPort));
880                    portletPreferences.setValue(
881                            PropsKeys.MAIL_SESSION_MAIL_SMTP_USER, smtpUser);
882                    portletPreferences.setValue(
883                            PropsKeys.MAIL_SESSION_MAIL_STORE_PROTOCOL, storeProtocol);
884                    portletPreferences.setValue(
885                            PropsKeys.MAIL_SESSION_MAIL_TRANSPORT_PROTOCOL, transportProtocol);
886    
887                    portletPreferences.store();
888    
889                    MailServiceUtil.clearSession();
890            }
891    
892            protected void validateCaptcha(ActionRequest actionRequest)
893                    throws Exception {
894    
895                    boolean reCaptchaEnabled = ParamUtil.getBoolean(
896                            actionRequest, "reCaptchaEnabled");
897    
898                    if (!reCaptchaEnabled) {
899                            return;
900                    }
901    
902                    String reCaptchaPrivateKey = ParamUtil.getString(
903                            actionRequest, "reCaptchaPrivateKey");
904                    String reCaptchaPublicKey = ParamUtil.getString(
905                            actionRequest, "reCaptchaPublicKey");
906    
907                    if (Validator.isNull(reCaptchaPublicKey)) {
908                            SessionErrors.add(actionRequest, "reCaptchaPublicKey");
909                    }
910                    else if (Validator.isNull(reCaptchaPrivateKey)) {
911                            SessionErrors.add(actionRequest, "reCaptchaPrivateKey");
912                    }
913            }
914    
915            protected void verifyMembershipPolicies() throws Exception {
916                    OrganizationMembershipPolicy organizationMembershipPolicy =
917                            OrganizationMembershipPolicyFactoryUtil.
918                                    getOrganizationMembershipPolicy();
919    
920                    organizationMembershipPolicy.verifyPolicy();
921    
922                    RoleMembershipPolicy roleMembershipPolicy =
923                            RoleMembershipPolicyFactoryUtil.getRoleMembershipPolicy();
924    
925                    roleMembershipPolicy.verifyPolicy();
926    
927                    SiteMembershipPolicy siteMembershipPolicy =
928                            SiteMembershipPolicyFactoryUtil.getSiteMembershipPolicy();
929    
930                    siteMembershipPolicy.verifyPolicy();
931    
932                    UserGroupMembershipPolicy userGroupMembershipPolicy =
933                            UserGroupMembershipPolicyFactoryUtil.getUserGroupMembershipPolicy();
934    
935                    userGroupMembershipPolicy.verifyPolicy();
936            }
937    
938            protected void verifyPluginTables() throws Exception {
939                    ServiceComponentLocalServiceUtil.verifyDB();
940            }
941    
942            private static Log _log = LogFactoryUtil.getLog(EditServerAction.class);
943    
944            private static MethodKey _loadIndexesFromClusterMethodKey = new MethodKey(
945                    LuceneClusterUtil.class, "loadIndexesFromCluster", long[].class,
946                    Address.class);
947    
948            private static class ClusterLoadingSyncJob implements Runnable {
949    
950                    public ClusterLoadingSyncJob(
951                            long[] companyIds, CountDownLatch countDownLatch, boolean master) {
952    
953                            _companyIds = companyIds;
954                            _countDownLatch = countDownLatch;
955                            _master = master;
956                    }
957    
958                    @Override
959                    public void run() {
960                            _countDownLatch.countDown();
961    
962                            String logPrefix = StringPool.BLANK;
963    
964                            if (_log.isInfoEnabled()) {
965                                    Thread currentThread = Thread.currentThread();
966    
967                                    if (_master) {
968                                            logPrefix =
969                                                    "Monitor thread name " + currentThread.getName() +
970                                                            " with thread ID " + currentThread.getId();
971                                    }
972                                    else {
973                                            logPrefix =
974                                                    "Thread name " + currentThread.getName() +
975                                                            " with thread ID " + currentThread.getId();
976                                    }
977                            }
978    
979                            if (!_master && _log.isInfoEnabled()) {
980                                    _log.info(
981                                            logPrefix + " synchronized on latch. Waiting for others.");
982                            }
983    
984                            try {
985                                    if (_master) {
986                                            _countDownLatch.await();
987                                    }
988                                    else {
989                                            boolean result = _countDownLatch.await(
990                                                    PropsValues.LUCENE_CLUSTER_INDEX_LOADING_SYNC_TIMEOUT,
991                                                    TimeUnit.MILLISECONDS);
992    
993                                            if (!result) {
994                                                    _log.error(
995                                                            logPrefix + " timed out. You may need to " +
996                                                                    "re-trigger a reindex process.");
997                                            }
998                                    }
999                            }
1000                            catch (InterruptedException ie) {
1001                                    if (_master) {
1002                                            _log.error(
1003                                                    logPrefix + " was interrupted. Skip cluster index " +
1004                                                            "loading notification.",
1005                                                    ie);
1006    
1007                                            return;
1008                                    }
1009                                    else {
1010                                            _log.error(
1011                                                    logPrefix + " was interrupted. You may need to " +
1012                                                            "re-trigger a reindex process.",
1013                                                    ie);
1014                                    }
1015                            }
1016    
1017                            if (_master) {
1018                                    Address localClusterNodeAddress =
1019                                            ClusterExecutorUtil.getLocalClusterNodeAddress();
1020    
1021                                    ClusterRequest clusterRequest =
1022                                            ClusterRequest.createMulticastRequest(
1023                                                    new MethodHandler(
1024                                                            _loadIndexesFromClusterMethodKey, _companyIds,
1025                                                            localClusterNodeAddress),
1026                                                    true);
1027    
1028                                    try {
1029                                            ClusterExecutorUtil.execute(clusterRequest);
1030                                    }
1031                                    catch (SystemException se) {
1032                                            _log.error(
1033                                                    "Unable to notify peers to start index loading", se);
1034                                    }
1035    
1036                                    if (_log.isInfoEnabled()) {
1037                                            _log.info(
1038                                                    logPrefix + " unlocked latch. Notified peers to " +
1039                                                            "start index loading.");
1040                                    }
1041                            }
1042                    }
1043    
1044                    private long[] _companyIds;
1045                    private CountDownLatch _countDownLatch;
1046                    private boolean _master;
1047    
1048            }
1049    
1050    }