001/*
002    Licensed to the Apache Software Foundation (ASF) under one
003    or more contributor license agreements.  See the NOTICE file
004    distributed with this work for additional information
005    regarding copyright ownership.  The ASF licenses this file
006    to you under the Apache License, Version 2.0 (the
007    "License"); you may not use this file except in compliance
008    with the License.  You may obtain a copy of the License at
009
010       http://www.apache.org/licenses/LICENSE-2.0
011
012    Unless required by applicable law or agreed to in writing,
013    software distributed under the License is distributed on an
014    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015    KIND, either express or implied.  See the License for the
016    specific language governing permissions and limitations
017    under the License.
018 */
019package org.apache.wiki.notification;
020
021import org.apache.logging.log4j.LogManager;
022import org.apache.logging.log4j.Logger;
023import org.apache.wiki.api.core.Acl;
024import org.apache.wiki.api.core.ContextEnum;
025import org.apache.wiki.api.core.Engine;
026import org.apache.wiki.api.core.Page;
027import org.apache.wiki.api.engine.Initializable;
028import org.apache.wiki.api.exceptions.WikiException;
029import org.apache.wiki.auth.UserManager;
030import org.apache.wiki.auth.acl.AclManager;
031import org.apache.wiki.auth.permissions.PermissionFactory;
032import org.apache.wiki.auth.user.UserDatabase;
033import org.apache.wiki.auth.user.UserProfile;
034import org.apache.wiki.event.WikiEvent;
035import org.apache.wiki.event.WikiEventListener;
036import org.apache.wiki.event.WikiEventManager;
037import org.apache.wiki.event.WikiPageEvent;
038import org.apache.wiki.filters.FilterManager;
039import org.apache.wiki.i18n.InternationalizationManager;
040import org.apache.wiki.pages.PageManager;
041import org.apache.wiki.util.MailUtil;
042import org.apache.wiki.util.TextUtil;
043
044import java.security.Principal;
045import java.util.ArrayList;
046import java.util.Collections;
047import java.util.LinkedHashSet;
048import java.util.List;
049import java.util.Locale;
050import java.util.Properties;
051import java.util.Set;
052import java.util.concurrent.ExecutorService;
053import java.util.concurrent.Executors;
054
055/**
056 * Default implementation of {@link SubscriptionManager}. It listens to the end of the post-save filtering and sends an
057 * e-mail to every user that is subscribed to the saved page and has an e-mail address in the profile.
058 * <p>
059 * The mails are sent from a single background thread, so saving a page never waits for the mail server. The mail does not
060 * contain the text of the page. The links in the mails are made absolute with the property {@value #PROP_BASEURL}, since no
061 * request is available here. Pages with an ACL on the view permission are not notified, since the view permission of an
062 * offline user cannot be evaluated here.
063 *
064 * @since 3.0.1
065 */
066public class DefaultSubscriptionManager implements SubscriptionManager, Initializable, WikiEventListener {
067
068    private static final Logger LOG = LogManager.getLogger( DefaultSubscriptionManager.class );
069
070    /** Separates the page names in the profile attribute; it cannot be part of a page name. */
071    private static final String SEPARATOR = "\n";
072
073    /** Scheme and host of the links in the mails, like <tt>https://wiki.example.org</tt>. Value is <tt>{@value}</tt>. */
074    public static final String PROP_BASEURL = "jspwiki.subscription.baseURL";
075
076    private Engine m_engine;
077    private ExecutorService m_executor;
078    private String m_baseUrl;
079
080    /**
081     * {@inheritDoc}
082     */
083    @Override
084    public void initialize( final Engine engine, final Properties props ) throws WikiException {
085        m_engine = engine;
086        m_baseUrl = TextUtil.getStringProperty( props, PROP_BASEURL, "" ).replaceAll( "/+$", "" );
087        m_executor = Executors.newSingleThreadExecutor( r -> {
088            final Thread t = new Thread( r, "JSPWiki subscription notifier" );
089            t.setDaemon( true );
090            return t;
091        } );
092        // the FilterManager is the source of the save events and it is set up before this component
093        WikiEventManager.addWikiEventListener( engine.getManager( FilterManager.class ), this );
094    }
095
096    /**
097     * {@inheritDoc}
098     */
099    @Override
100    public void subscribe( final String loginName, final String pageName ) throws WikiException {
101        final UserProfile profile = findProfile( loginName );
102        final Set< String > pages = readSubscriptions( profile );
103        if( pages.add( pageName ) ) {
104            storeSubscriptions( profile, pages );
105        }
106    }
107
108    /**
109     * {@inheritDoc}
110     */
111    @Override
112    public void unsubscribe( final String loginName, final String pageName ) throws WikiException {
113        final UserProfile profile = findProfile( loginName );
114        final Set< String > pages = readSubscriptions( profile );
115        if( pages.remove( pageName ) ) {
116            storeSubscriptions( profile, pages );
117        }
118    }
119
120    /**
121     * {@inheritDoc}
122     */
123    @Override
124    public boolean isSubscribed( final String loginName, final String pageName ) {
125        return getSubscriptions( loginName ).contains( pageName );
126    }
127
128    /**
129     * {@inheritDoc}
130     */
131    @Override
132    public Set< String > getSubscriptions( final String loginName ) {
133        try {
134            return Collections.unmodifiableSet( readSubscriptions( findProfile( loginName ) ) );
135        } catch( final WikiException e ) {
136            return Collections.emptySet();
137        }
138    }
139
140    /**
141     * {@inheritDoc}
142     */
143    @Override
144    public void actionPerformed( final WikiEvent event ) {
145        if( event instanceof WikiPageEvent && event.getType() == WikiPageEvent.POST_SAVE_END ) {
146            final String pageName = ( ( WikiPageEvent )event ).getPageName();
147            m_executor.execute( () -> notifySubscribers( pageName ) );
148        }
149    }
150
151    void notifySubscribers( final String pageName ) {
152        try {
153            final UserDatabase db = m_engine.getManager( UserManager.class ).getUserDatabase();
154            final List< UserProfile > recipients = new ArrayList<>();
155            for( final Principal wikiName : db.getWikiNames() ) {
156                final UserProfile profile = db.findByWikiName( wikiName.getName() );
157                final String email = profile.getEmail();
158                if( email != null && !email.isEmpty() && readSubscriptions( profile ).contains( pageName ) ) {
159                    recipients.add( profile );
160                }
161            }
162            if( recipients.isEmpty() ) {
163                return;
164            }
165            // reading the page and looking up its ACL (which renders it) is only done when someone is going to be notified
166            final Page page = m_engine.getManager( PageManager.class ).getPage( pageName );
167            if( page == null || isViewRestricted( page ) ) {
168                return;
169            }
170            for( final UserProfile profile : recipients ) {
171                sendMail( profile, page );
172            }
173        } catch( final Exception e ) {
174            LOG.error( "Could not notify the subscribers of " + pageName, e );
175        }
176    }
177
178    private boolean isViewRestricted( final Page page ) {
179        final Acl acl = m_engine.getManager( AclManager.class ).getPermissions( page );
180        return acl != null && acl.findPrincipals( PermissionFactory.getPagePermission( page, "view" ) ).length > 0;
181    }
182
183    private void sendMail( final UserProfile profile, final Page page ) {
184        try {
185            final InternationalizationManager i18n = m_engine.getManager( InternationalizationManager.class );
186            final Locale locale = Locale.getDefault();
187            final String app = m_engine.getApplicationName();
188            final String url = m_engine.getURL( ContextEnum.PAGE_VIEW.getRequestContext(), page.getName(), null );
189            final String author = page.getAuthor() == null ? "" : page.getAuthor();
190            final String subject = i18n.get( InternationalizationManager.DEF_TEMPLATE, locale,
191                                             "notification.pageChanged.subject", app, page.getName() );
192            final String content = i18n.get( InternationalizationManager.DEF_TEMPLATE, locale,
193                                             "notification.pageChanged.content", app, page.getName(), author, m_baseUrl + url );
194            MailUtil.sendMessage( m_engine.getWikiProperties(), profile.getEmail(), subject, content );
195        } catch( final Exception e ) {
196            LOG.warn( "Could not send the change notification of {} to {}: {}", page.getName(), profile.getLoginName(), e.getMessage() );
197        }
198    }
199
200    private UserProfile findProfile( final String loginName ) throws WikiException {
201        return m_engine.getManager( UserManager.class ).getUserDatabase().findByLoginName( loginName );
202    }
203
204    private static Set< String > readSubscriptions( final UserProfile profile ) {
205        final Set< String > pages = new LinkedHashSet<>();
206        final Object stored = profile.getAttributes().get( PROFILE_ATTR_SUBSCRIPTIONS );
207        if( stored instanceof String && !( ( String )stored ).isEmpty() ) {
208            Collections.addAll( pages, ( ( String )stored ).split( SEPARATOR ) );
209        }
210        return pages;
211    }
212
213    private void storeSubscriptions( final UserProfile profile, final Set< String > pages ) throws WikiException {
214        if( pages.isEmpty() ) {
215            profile.getAttributes().remove( PROFILE_ATTR_SUBSCRIPTIONS );
216        } else {
217            profile.getAttributes().put( PROFILE_ATTR_SUBSCRIPTIONS, String.join( SEPARATOR, pages ) );
218        }
219        m_engine.getManager( UserManager.class ).getUserDatabase().save( profile );
220    }
221
222}