xref: /dokuwiki/inc/Subscriptions/BulkSubscriptionSender.php (revision 8c7c53b0321a3cd3116b8d3b2ad27863a38dece7)
1<?php
2
3
4namespace dokuwiki\Subscriptions;
5
6
7use dokuwiki\ChangeLog\PageChangeLog;
8use dokuwiki\Input\Input;
9
10class BulkSubscriptionSender extends SubscriptionSender
11{
12
13    /**
14     * Send digest and list subscriptions
15     *
16     * This sends mails to all subscribers that have a subscription for namespaces above
17     * the given page if the needed $conf['subscribe_time'] has passed already.
18     *
19     * This function is called form lib/exe/indexer.php
20     *
21     * @param string $page
22     *
23     * @return int number of sent mails
24     */
25    public function sendBulk($page)
26    {
27        $subscriberManager = new SubscriberManager();
28        if (!$subscriberManager->isenabled()) {
29            return 0;
30        }
31
32        /** @var DokuWiki_Auth_Plugin $auth */
33        global $auth;
34        global $conf;
35        global $USERINFO;
36        /** @var Input $INPUT */
37        global $INPUT;
38        $count = 0;
39
40        $subscriptions = $subscriberManager->subscribers($page, null, ['digest', 'list']);
41
42        // remember current user info
43        $olduinfo = $USERINFO;
44        $olduser = $INPUT->server->str('REMOTE_USER');
45
46        foreach ($subscriptions as $target => $users) {
47            if (!$this->lock($target)) {
48                continue;
49            }
50
51            foreach ($users as $user => $info) {
52                [$style, $lastupdate] = $info;
53
54                $lastupdate = (int)$lastupdate;
55                if ($lastupdate + $conf['subscribe_time'] > time()) {
56                    // Less than the configured time period passed since last
57                    // update.
58                    continue;
59                }
60
61                // Work as the user to make sure ACLs apply correctly
62                $USERINFO = $auth->getUserData($user);
63                $INPUT->server->set('REMOTE_USER', $user);
64                if ($USERINFO === false) {
65                    continue;
66                }
67                if (!$USERINFO['mail']) {
68                    continue;
69                }
70
71                if (substr($target, -1, 1) === ':') {
72                    // subscription target is a namespace, get all changes within
73                    $changes = getRecentsSince($lastupdate, null, getNS($target));
74                } else {
75                    // single page subscription, check ACL ourselves
76                    if (auth_quickaclcheck($target) < AUTH_READ) {
77                        continue;
78                    }
79                    $meta = p_get_metadata($target);
80                    $changes = [$meta['last_change']];
81                }
82
83                // Filter out pages only changed in small and own edits
84                $change_ids = [];
85                foreach ($changes as $rev) {
86                    $n = 0;
87                    $pagelog = new PageChangeLog($rev['id']);
88                    while (!is_null($rev) && $rev['date'] >= $lastupdate &&
89                        ($INPUT->server->str('REMOTE_USER') === $rev['user'] ||
90                            $rev['type'] === DOKU_CHANGE_TYPE_MINOR_EDIT)
91                    ) {
92                        $revisions = $pagelog->getRevisions($n++, 1);
93                        $rev = ($revisions !== []) ? $pagelog->getRevisionInfo($revisions[0]) : null;
94                    }
95
96                    if (!is_null($rev) && $rev['date'] >= $lastupdate) {
97                        // Some change was not a minor one and not by myself
98                        $change_ids[] = $rev['id'];
99                    }
100                }
101
102                // send it
103                if ($style === 'digest') {
104                    foreach ($change_ids as $change_id) {
105                        $this->sendDigest(
106                            $USERINFO['mail'],
107                            $change_id,
108                            $lastupdate
109                        );
110                        $count++;
111                    }
112                } elseif ($style === 'list') {
113                    $this->sendList($USERINFO['mail'], $change_ids, $target);
114                    $count++;
115                }
116                // TODO: Handle duplicate subscriptions.
117
118                // Update notification time.
119                $subscriberManager->add($target, $user, $style, time());
120            }
121            $this->unlock($target);
122        }
123
124        // restore current user info
125        $USERINFO = $olduinfo;
126        $INPUT->server->set('REMOTE_USER', $olduser);
127        return $count;
128    }
129
130    /**
131     * Lock subscription info
132     *
133     * We don't use io_lock() her because we do not wait for the lock and use a larger stale time
134     *
135     * @param string $id The target page or namespace, specified by id; Namespaces
136     *                   are identified by appending a colon.
137     *
138     * @return bool true, if you got a succesful lock
139     * @author Adrian Lang <lang@cosmocode.de>
140     */
141    protected function lock($id)
142    {
143        global $conf;
144
145        $lock = $conf['lockdir'] . '/_subscr_' . md5($id) . '.lock';
146
147        if (is_dir($lock) && time() - @filemtime($lock) > 60 * 5) {
148            // looks like a stale lock - remove it
149            @rmdir($lock);
150        }
151
152        // try creating the lock directory
153        if (!@mkdir($lock)) {
154            return false;
155        }
156
157        if ($conf['dperm']) {
158            chmod($lock, $conf['dperm']);
159        }
160        return true;
161    }
162
163    /**
164     * Unlock subscription info
165     *
166     * @param string $id The target page or namespace, specified by id; Namespaces
167     *                   are identified by appending a colon.
168     *
169     * @return bool
170     * @author Adrian Lang <lang@cosmocode.de>
171     */
172    protected function unlock($id)
173    {
174        global $conf;
175        $lock = $conf['lockdir'] . '/_subscr_' . md5($id) . '.lock';
176        return @rmdir($lock);
177    }
178
179    /**
180     * Send a digest mail
181     *
182     * Sends a digest mail showing a bunch of changes of a single page. Basically the same as sendPageDiff()
183     * but determines the last known revision first
184     *
185     * @param string $subscriber_mail The target mail address
186     * @param string $id              The ID
187     * @param int    $lastupdate      Time of the last notification
188     *
189     * @return bool
190     * @author Adrian Lang <lang@cosmocode.de>
191     *
192     */
193    protected function sendDigest($subscriber_mail, $id, $lastupdate)
194    {
195        $pagelog = new PageChangeLog($id);
196        $n = 0;
197        do {
198            $rev = $pagelog->getRevisions($n++, 1);
199            $rev = ($rev !== []) ? $rev[0] : null;
200        } while (!is_null($rev) && $rev > $lastupdate);
201
202        // TODO I'm not happy with the following line and passing $this->mailer around. Not sure how to solve it better
203        $pageSubSender = new PageSubscriptionSender($this->mailer);
204        return $pageSubSender->sendPageDiff(
205            $subscriber_mail,
206            'subscr_digest',
207            $id,
208            $rev
209        );
210    }
211
212    /**
213     * Send a list mail
214     *
215     * Sends a list mail showing a list of changed pages.
216     *
217     * @param string $subscriber_mail The target mail address
218     * @param array  $ids             Array of ids
219     * @param string $ns_id           The id of the namespace
220     *
221     * @return bool true if a mail was sent
222     * @author Adrian Lang <lang@cosmocode.de>
223     *
224     */
225    protected function sendList($subscriber_mail, $ids, $ns_id)
226    {
227        if ($ids === []) {
228            return false;
229        }
230
231        $tlist = '';
232        $hlist = '<ul>';
233        foreach ($ids as $id) {
234            $link = wl($id, [], true);
235            $tlist .= '* ' . $link . NL;
236            $hlist .= '<li><a href="' . $link . '">' . hsc($id) . '</a></li>' . NL;
237        }
238        $hlist .= '</ul>';
239
240        $id = prettyprint_id($ns_id);
241        $trep = [
242            'DIFF' => rtrim($tlist),
243            'PAGE' => $id,
244            'SUBSCRIBE' => wl($id, ['do' => 'subscribe'], true, '&'),
245        ];
246        $hrep = [
247            'DIFF' => $hlist,
248        ];
249
250        return $this->send(
251            $subscriber_mail,
252            'subscribe_list',
253            $ns_id,
254            'subscr_list',
255            $trep,
256            $hrep
257        );
258    }
259}
260