]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/MailNotify.php
Allow bold, italics or underlined for numbers
[SourceForge/phpwiki.git] / lib / MailNotify.php
1 <?php
2
3 /* Copyright (C) 2006-2007,2009 Reini Urban
4  * Copyright (C) 2009 Marc-Etienne Vargenau, Alcatel-Lucent
5  *
6  * This file is part of PhpWiki.
7  *
8  * PhpWiki is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * PhpWiki is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License along
19  * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
20  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21  */
22
23 /**
24  * Handle the pagelist pref[notifyPages] logic for users
25  * and notify => hash ( page => (userid => userhash) ) for pages.
26  * Generate notification emails.
27  *
28  * We add WikiDB handlers and register ourself there:
29  *   onChangePage, onDeletePage, onRenamePage
30  * Administrative actions:
31  *   [Watch] WatchPage - add a page, or delete watch handlers into the users
32  *                       pref[notifyPages] slot.
33  *   My WatchList      - view or edit list/regex of pref[notifyPages].
34  *   EMailConfirm methods: send and verify
35  *
36  * Helper functions:
37  *   getPageChangeEmails
38  *   MailAdmin
39  *   ? handle emailed confirmation links (EmailSignup, ModeratedPage)
40  *
41  * @package MailNotify
42  * @author  Reini Urban
43  */
44
45 if (!defined("MAILER_LOG")) {
46     if (isWindows()) {
47         define("MAILER_LOG", 'c:/wikimail.log');
48     } else {
49         define("MAILER_LOG", '/var/log/wikimail.log');
50     }
51 }
52
53 class MailNotify
54 {
55
56     function MailNotify($pagename)
57     {
58         $this->pagename = $pagename; /* which page */
59         $this->emails = array(); /* to which addresses */
60         $this->userids = array(); /* corresponding array of displayed names,
61                                         don't display the email addresses */
62         /* From: from whom the mail appears to be */
63         $this->from = $this->fromId();
64     }
65
66     function fromId()
67     {
68         global $request;
69         if (defined('FUSIONFORGE') and FUSIONFORGE) {
70             return $request->_user->getId();
71         } else {
72             return $request->_user->getId() . '@' . $request->get('REMOTE_HOST');
73         }
74     }
75
76     function fromEmail()
77     {
78         global $request;
79         return $this->userEmail($request->_user->getId(), false);
80     }
81
82     function userEmail($userid, $doverify = true)
83     {
84         global $request;
85
86         // Disable verification of emails for corporate env.
87         if (defined('FUSIONFORGE') and FUSIONFORGE) {
88             $doverify = false;
89         }
90
91         $u = $request->getUser();
92         if ($u->UserName() == $userid) { // lucky: current user
93             $prefs = $u->getPreferences();
94             $email = $prefs->get('email');
95             // do a dynamic emailVerified check update
96             if ($doverify and !$request->_prefs->get('emailVerified')) {
97                 $email = '';
98             }
99         } else { // not current user
100             if (ENABLE_USER_NEW) {
101                 $u = WikiUser($userid);
102                 $u->getPreferences();
103                 $prefs = &$u->_prefs;
104             } else {
105                 $u = new WikiUser($request, $userid);
106                 $prefs = $u->getPreferences();
107             }
108             $email = $prefs->get('email');
109             if ($doverify and !$prefs->get('emailVerified')) {
110                 $email = '';
111             }
112         }
113         return $email;
114     }
115
116     /**
117      * getPageChangeEmails($notify)
118      * @param  $notify: hash ( page => (userid => userhash) )
119      * @return array
120      *         unique array of ($emails, $userids)
121      */
122     function getPageChangeEmails($notify)
123     {
124         global $request;
125         $emails = array();
126         $userids = array();
127         foreach ($notify as $page => $users) {
128             if (glob_match($page, $this->pagename)) {
129                 $curuser = $request->getUser();
130                 $curuserprefs = $curuser->getPreferences();
131                 $curuserprefsemail = $curuserprefs->get('email');
132                 $ownModifications = $curuserprefs->get('ownModifications');
133                 $majorModificationsOnly = $curuserprefs->get('majorModificationsOnly');
134
135                 foreach ($users as $userid => $user) {
136
137                     $usermail = $user['email'];
138
139                     if (($usermail == $curuserprefsemail)
140                         and ($ownModifications)
141                     ) {
142                         // It's my own modification
143                         // and I do not want to receive it
144                         continue;
145                     }
146
147                     if ($majorModificationsOnly) {
148                         $backend = &$request->_dbi->_backend;
149                         $version = $backend->get_latest_version($this->pagename);
150                         $versiondata = $backend->get_versiondata($this->pagename, $version, true);
151                         if ($versiondata['is_minor_edit']) {
152                             // It's a minor modification
153                             // and I do not want to receive it
154                             continue;
155                         }
156                     }
157
158                     if (!$user) { // handle the case for ModeratePage:
159                         // no prefs, just userid's.
160                         $emails[] = $this->userEmail($userid, false);
161                         $userids[] = $userid;
162                     } else {
163                         if (!empty($user['verified']) and !empty($user['email'])) {
164                             $emails[] = $user['email'];
165                             $userids[] = $userid;
166                         } elseif (!empty($user['email'])) {
167                             // do a dynamic emailVerified check update
168                             $email = $this->userEmail($userid, true);
169                             if ($email) {
170                                 $notify[$page][$userid]['verified'] = 1;
171                                 $request->_dbi->set('notify', $notify);
172                                 $emails[] = $email;
173                                 $userids[] = $userid;
174                             }
175                         }
176                     }
177                 }
178             }
179         }
180         $this->emails = array_unique($emails);
181         $this->userids = array_unique($userids);
182         return array($this->emails, $this->userids);
183     }
184
185     function sendMail($subject,
186                       $content,
187                       $notice = false,
188                       $silent = true)
189     {
190         // Add WIKI_NAME to Subject
191         $subject = "[" . WIKI_NAME . "] " . $subject;
192         // Encode $subject if needed
193         $encoded_subject = $this->subject_encode($subject);
194         $emails = $this->emails;
195         // Do not send if modification is from FusionForge admin
196         if ((defined('FUSIONFORGE') and FUSIONFORGE) and ($this->fromId() == ADMIN_USER)) {
197             return true;
198         }
199         if (!$notice) {
200             $notice = _("PageChange Notification of %s");
201         }
202         $from = $this->fromEmail();
203         $headers = "From: $from\r\n" .
204             "Bcc: " . join(',', $emails) . "\r\n" .
205             "MIME-Version: 1.0\r\n" .
206             "Content-Type: text/plain; charset=UTF-8; format=flowed\r\n" .
207             "Content-Transfer-Encoding: 8bit";
208
209         $ok = mail(($to = array_shift($emails)),
210             $encoded_subject,
211             $subject . "\n" . $content,
212             $headers
213         );
214         if (MAILER_LOG and is_writable(MAILER_LOG)) {
215             global $ErrorManager;
216
217             $f = fopen(MAILER_LOG, "a");
218             fwrite($f, "\n\nX-MailSentOK: " . $ok ? 'OK' : 'FAILED');
219
220             if (!$ok && isset($ErrorManager->_postponed_errors[count($ErrorManager->_postponed_errors) - 1])) {
221                 // get last error message
222                 $last_err = $ErrorManager->_postponed_errors[count($ErrorManager->_postponed_errors) - 1];
223                 fwrite($f, "\nX-MailFailure: " .
224                     "errno: " . $last_err->errno . ", " .
225                     "errstr: " . $last_err->errstr . ", " .
226                     "errfile: " . $last_err->errfile . ", " .
227                     "errline: " . $last_err->errline);
228             }
229             fwrite($f, "\nDate: " . CTime());
230             fwrite($f, "\nSubject: $encoded_subject");
231             fwrite($f, "\nFrom: $from");
232             fwrite($f, "\nTo: $to");
233             fwrite($f, "\nBcc: " . join(',', $emails));
234             fwrite($f, "\n\n" . $content);
235             fclose($f);
236         }
237         if ($ok) {
238             if (!$silent)
239                 trigger_error(sprintf($notice, $this->pagename)
240                         . " "
241                         . sprintf(_("sent to %s"), join(',', $this->userids)),
242                     E_USER_NOTICE);
243             return true;
244         } else {
245             trigger_error(sprintf($notice, $this->pagename)
246                     . " "
247                     . sprintf(_("Error: Couldn't send %s to %s"),
248                         $subject . "\n" . $content, join(',', $this->userids)),
249                 E_USER_WARNING);
250             return false;
251         }
252     }
253
254     /**
255      * Send udiff for a changed page to multiple users.
256      * See rename and remove methods also
257      */
258     function sendPageChangeNotification(&$wikitext, $version, &$meta)
259     {
260
261         global $request;
262
263         if (isset($request->_deferredPageChangeNotification)) {
264             // collapse multiple changes (loaddir) into one email
265             $request->_deferredPageChangeNotification[] =
266                 array($this->pagename, $this->emails, $this->userids);
267             return;
268         }
269         $backend = &$request->_dbi->_backend;
270         $previous = $backend->get_previous_version($this->pagename, $version);
271         if (!isset($meta['mtime'])) {
272             $meta['mtime'] = time();
273         }
274         if ($previous) {
275             // Page existed, and was modified
276             $subject = _("Page change") . ' ' . ($this->pagename);
277             $difflink = WikiURL($this->pagename, array('action' => 'diff'), true);
278             $cache = &$request->_dbi->_cache;
279             $this_content = explode("\n", $wikitext);
280             $prevdata = $cache->get_versiondata($this->pagename, $previous, true);
281             if (empty($prevdata['%content'])) {
282                 $prevdata = $backend->get_versiondata($this->pagename, $previous, true);
283             }
284             $other_content = explode("\n", $prevdata['%content']);
285
286             include_once 'lib/difflib.php';
287             $diff2 = new Diff($other_content, $this_content);
288             //$context_lines = max(4, count($other_content) + 1,
289             //                     count($this_content) + 1);
290             $fmt = new UnifiedDiffFormatter( /*$context_lines*/);
291             $content = $this->pagename . " " . $previous . " " .
292                 Iso8601DateTime($prevdata['mtime']) . "\n";
293             $content .= $this->pagename . " " . $version . " " .
294                 Iso8601DateTime($meta['mtime']) . "\n";
295             $content .= $fmt->format($diff2);
296             $editedby = sprintf(_("Edited by: %s"), $this->fromId());
297         } else {
298             // Page did not exist, and was created
299             $subject = _("Page creation") . ' ' . ($this->pagename);
300             $difflink = WikiURL($this->pagename, array(), true);
301             $content = $this->pagename . " " . $version . " " .
302                 Iso8601DateTime($meta['mtime']) . "\n";
303             $content .= _("New page");
304             $content .= "\n\n";
305             $content .= $wikitext;
306             $editedby = sprintf(_("Created by: %s"), $this->fromId());
307         }
308         $summary = sprintf(_("Summary: %s"), $meta['summary']);
309         $this->sendMail($subject,
310             $editedby . "\n" . $summary . "\n" . $difflink . "\n\n" . $content);
311     }
312
313     /**
314      * Support mass rename / remove (TBD)
315      */
316     function sendPageRenameNotification($to)
317     {
318         $pagename = $this->pagename;
319         $editedby = sprintf(_("Renamed by: %s"), $this->fromId());
320         $subject = sprintf(_("Page rename %s to %s"), $pagename, $to);
321         $link = WikiURL($to, true);
322         $this->sendMail($subject,
323             $editedby . "\n" . $link . "\n\n" . "Renamed $pagename to $to");
324     }
325
326     /**
327      * The handlers:
328      */
329     function onChangePage(&$wikidb, &$wikitext, $version, &$meta)
330     {
331         if (!isa($GLOBALS['request'], 'MockRequest')) {
332             $notify = $wikidb->get('notify');
333             /* Generate notification emails? */
334             if (!empty($notify) and is_array($notify)) {
335                 if (empty($this->pagename))
336                     $this->pagename = $meta['pagename'];
337                 // TODO: Should be used for ModeratePage and RSS2 Cloud xml-rpc also.
338                 $this->getPageChangeEmails($notify);
339                 if (!empty($this->emails)) {
340                     $this->sendPageChangeNotification($wikitext, $version, $meta);
341                 }
342             }
343         }
344     }
345
346     function onDeletePage(&$wikidb, $pagename)
347     {
348         $result = true;
349         /* Generate notification emails? */
350         if (!$wikidb->isWikiPage($pagename) and !isa($GLOBALS['request'], 'MockRequest')) {
351             $notify = $wikidb->get('notify');
352             if (!empty($notify) and is_array($notify)) {
353                 //TODO: deferr it (quite a massive load if you remove some pages).
354                 $this->getPageChangeEmails($notify);
355                 if (!empty($this->emails)) {
356                     $subject = sprintf(_("User %s removed page %s"), $this->fromId(), $pagename);
357                     $result = $this->sendMail($subject, $subject . "\n\n");
358                 }
359             }
360         }
361         return $result;
362     }
363
364     function onRenamePage(&$wikidb, $oldpage, $new_pagename)
365     {
366         if (!isa($GLOBALS['request'], 'MockRequest')) {
367             $notify = $wikidb->get('notify');
368             if (!empty($notify) and is_array($notify)) {
369                 $this->getPageChangeEmails($notify);
370                 if (!empty($this->emails)) {
371                     $this->pagename = $oldpage;
372                     $this->sendPageRenameNotification($new_pagename);
373                 }
374             }
375         }
376     }
377
378     /**
379      * Send mail to user and store the cookie in the db
380      * wikiurl?action=ConfirmEmail&id=bla
381      */
382     function sendEmailConfirmation($email, $userid)
383     {
384         global $request;
385         $id = rand_ascii_readable(16);
386         $wikidb = $request->getDbh();
387         $data = $wikidb->get('ConfirmEmail');
388         while (!empty($data[$id])) { // id collision
389             $id = rand_ascii_readable(16);
390         }
391         $subject = _("E-mail address confirmation");
392         $ip = $request->get('REMOTE_HOST');
393         $expire_date = time() + 7 * 86400;
394         $content = fmt("Someone, probably you from IP address %s, has registered an
395 account \"%s\" with this e-mail address on %s.
396
397 To confirm that this account really does belong to you and activate
398 e-mail features on %s, open this link in your browser:
399
400 %s
401
402 If this is *not* you, don't follow the link. This confirmation code
403 will expire at %s.",
404             $ip, $userid, WIKI_NAME, WIKI_NAME,
405             WikiURL(HOME_PAGE, array('action' => 'ConfirmEmail',
406                     'id' => $id),
407                 true),
408             CTime($expire_date));
409         $this->sendMail($subject, $content, "", true);
410         $data[$id] = array('email' => $email,
411             'userid' => $userid,
412             'expire' => $expire_date);
413         $wikidb->set('ConfirmEmail', $data);
414         return '';
415     }
416
417     function checkEmailConfirmation()
418     {
419         global $request;
420         $wikidb = $request->getDbh();
421         $data = $wikidb->get('ConfirmEmail');
422         $id = $request->getArg('id');
423         if (empty($data[$id])) { // id not found
424             return HTML(HTML::h1("Confirm E-mail address"),
425                 HTML::h1("Sorry! Wrong URL"));
426         }
427         // upgrade the user
428         $userid = $data['userid'];
429         $u = $request->getUser();
430         if ($u->UserName() == $userid) { // lucky: current user (session)
431             $request->_user->_level = WIKIAUTH_USER;
432             $request->_prefs->set('emailVerified', true);
433         } else { // not current user
434             if (ENABLE_USER_NEW) {
435                 $u = WikiUser($userid);
436                 $u->getPreferences();
437             } else {
438                 $u = new WikiUser($request, $userid);
439             }
440             $u->_level = WIKIAUTH_USER;
441             $request->setUser($u);
442             $request->_prefs->set('emailVerified', true);
443         }
444         unset($data[$id]);
445         $wikidb->set('ConfirmEmail', $data);
446         return HTML(HTML::h1("Confirm E-mail address"),
447             HTML::p("Your e-mail address has now been confirmed."));
448     }
449
450     function subject_encode($subject)
451     {
452         // We need to encode the subject if it contains non-ASCII characters
453         // The page name may contain non-ASCII characters, as well as
454         // the translation of the messages, e.g. _("PageChange Notification of %s");
455
456         // If all characters are ASCII, do nothing
457         if (isAsciiString($subject)) {
458             return $subject;
459         }
460
461         // Let us try quoted printable first
462         if (function_exists('quoted_printable_encode')) { // PHP 5.3
463             // quoted_printable_encode inserts "\r\n" if line is too long, use "\n" only
464             return "=?UTF-8?Q?" . str_replace("\r\n", "\n", quoted_printable_encode($subject)) . "?=";
465         }
466
467         // If not, encode in base64 (less human-readable)
468         return "=?UTF-8?B?" . base64_encode($subject) . "?=";
469     }
470 }
471
472 // Local Variables:
473 // mode: php
474 // tab-width: 8
475 // c-basic-offset: 4
476 // c-hanging-comment-ender-p: nil
477 // indent-tabs-mode: nil
478 // End: