]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/MailNotify.php
Reformat code
[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 (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 (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
130                 global $request;
131                 $curuser = $request->getUser();
132                 $curusername = $curuser->UserName();
133                 $curuserprefs = $curuser->getPreferences();
134                 $curuserprefsemail = $curuserprefs->get('email');
135                 $ownModifications = $curuserprefs->get('ownModifications');
136                 $majorModificationsOnly = $curuserprefs->get('majorModificationsOnly');
137
138                 foreach ($users as $userid => $user) {
139
140                     $usermail = $user['email'];
141
142                     if (($usermail == $curuserprefsemail)
143                         and ($ownModifications)
144                     ) {
145                         // It's my own modification
146                         // and I do not want to receive it
147                         continue;
148                     }
149
150                     if ($majorModificationsOnly) {
151                         $backend = &$request->_dbi->_backend;
152                         $version = $backend->get_latest_version($this->pagename);
153                         $versiondata = $backend->get_versiondata($this->pagename, $version, true);
154                         if ($versiondata['is_minor_edit']) {
155                             // It's a minor modification
156                             // and I do not want to receive it
157                             continue;
158                         }
159                     }
160
161                     if (!$user) { // handle the case for ModeratePage:
162                         // no prefs, just userid's.
163                         $emails[] = $this->userEmail($userid, false);
164                         $userids[] = $userid;
165                     } else {
166                         if (!empty($user['verified']) and !empty($user['email'])) {
167                             $emails[] = $user['email'];
168                             $userids[] = $userid;
169                         } elseif (!empty($user['email'])) {
170                             // do a dynamic emailVerified check update
171                             $email = $this->userEmail($userid, true);
172                             if ($email) {
173                                 $notify[$page][$userid]['verified'] = 1;
174                                 $request->_dbi->set('notify', $notify);
175                                 $emails[] = $email;
176                                 $userids[] = $userid;
177                             }
178                         }
179                         // ignore verification
180                         /*
181                         if (DEBUG) {
182                             if (!in_array($user['email'], $emails))
183                                 $emails[] = $user['email'];
184                         }
185                         */
186                     }
187                 }
188             }
189         }
190         $this->emails = array_unique($emails);
191         $this->userids = array_unique($userids);
192         return array($this->emails, $this->userids);
193     }
194
195     function sendMail($subject,
196                       $content,
197                       $notice = false,
198                       $silent = true)
199     {
200         // Add WIKI_NAME to Subject
201         $subject = "[" . WIKI_NAME . "] " . $subject;
202         // Encode $subject if needed
203         $encoded_subject = $this->subject_encode($subject);
204         $emails = $this->emails;
205         // Do not send if modification is from FusionForge admin
206         if (FUSIONFORGE and ($this->fromId() == ADMIN_USER)) {
207             return;
208         }
209         if (!$notice) {
210             $notice = _("PageChange Notification of %s");
211         }
212         $from = $this->fromEmail();
213         $headers = "From: $from\r\n" .
214             "Bcc: " . join(',', $emails) . "\r\n" .
215             "MIME-Version: 1.0\r\n" .
216             "Content-Type: text/plain; charset=" . CHARSET . "; format=flowed\r\n" .
217             "Content-Transfer-Encoding: 8bit";
218
219         $ok = mail(($to = array_shift($emails)),
220             $encoded_subject,
221             $subject . "\n" . $content,
222             $headers
223         );
224         if (MAILER_LOG and is_writable(MAILER_LOG)) {
225             global $ErrorManager;
226
227             $f = fopen(MAILER_LOG, "a");
228             fwrite($f, "\n\nX-MailSentOK: " . $ok ? 'OK' : 'FAILED');
229
230             if (!$ok && isset($ErrorManager->_postponed_errors[count($ErrorManager->_postponed_errors) - 1])) {
231                 // get last error message
232                 $last_err = $ErrorManager->_postponed_errors[count($ErrorManager->_postponed_errors) - 1];
233                 fwrite($f, "\nX-MailFailure: " .
234                     "errno: " . $last_err->errno . ", " .
235                     "errstr: " . $last_err->errstr . ", " .
236                     "errfile: " . $last_err->errfile . ", " .
237                     "errline: " . $last_err->errline);
238             }
239             fwrite($f, "\nDate: " . CTime());
240             fwrite($f, "\nSubject: $encoded_subject");
241             fwrite($f, "\nFrom: $from");
242             fwrite($f, "\nTo: $to");
243             fwrite($f, "\nBcc: " . join(',', $emails));
244             fwrite($f, "\n\n" . $content);
245             fclose($f);
246         }
247         if ($ok) {
248             if (!$silent)
249                 trigger_error(sprintf($notice, $this->pagename)
250                         . " "
251                         . sprintf(_("sent to %s"), join(',', $this->userids)),
252                     E_USER_NOTICE);
253             return true;
254         } else {
255             trigger_error(sprintf($notice, $this->pagename)
256                     . " "
257                     . sprintf(_("Error: Couldn't send %s to %s"),
258                         $subject . "\n" . $content, join(',', $this->userids)),
259                 E_USER_WARNING);
260             return false;
261         }
262     }
263
264     /**
265      * Send udiff for a changed page to multiple users.
266      * See rename and remove methods also
267      */
268     function sendPageChangeNotification(&$wikitext, $version, &$meta)
269     {
270
271         global $request;
272
273         if (isset($request->_deferredPageChangeNotification)) {
274             // collapse multiple changes (loaddir) into one email
275             $request->_deferredPageChangeNotification[] =
276                 array($this->pagename, $this->emails, $this->userids);
277             return;
278         }
279         $backend = &$request->_dbi->_backend;
280         $previous = $backend->get_previous_version($this->pagename, $version);
281         if (!isset($meta['mtime'])) {
282             $meta['mtime'] = time();
283         }
284         if ($previous) {
285             // Page existed, and was modified
286             $subject = _("Page change") . ' ' . ($this->pagename);
287             $difflink = WikiURL($this->pagename, array('action' => 'diff'), true);
288             $cache = &$request->_dbi->_cache;
289             $this_content = explode("\n", $wikitext);
290             $prevdata = $cache->get_versiondata($this->pagename, $previous, true);
291             if (empty($prevdata['%content'])) {
292                 $prevdata = $backend->get_versiondata($this->pagename, $previous, true);
293             }
294             $other_content = explode("\n", $prevdata['%content']);
295
296             include_once 'lib/difflib.php';
297             $diff2 = new Diff($other_content, $this_content);
298             //$context_lines = max(4, count($other_content) + 1,
299             //                     count($this_content) + 1);
300             $fmt = new UnifiedDiffFormatter( /*$context_lines*/);
301             $content = $this->pagename . " " . $previous . " " .
302                 Iso8601DateTime($prevdata['mtime']) . "\n";
303             $content .= $this->pagename . " " . $version . " " .
304                 Iso8601DateTime($meta['mtime']) . "\n";
305             $content .= $fmt->format($diff2);
306             $editedby = sprintf(_("Edited by: %s"), $this->fromId());
307         } else {
308             // Page did not exist, and was created
309             $subject = _("Page creation") . ' ' . ($this->pagename);
310             $difflink = WikiURL($this->pagename, array(), true);
311             $content = $this->pagename . " " . $version . " " .
312                 Iso8601DateTime($meta['mtime']) . "\n";
313             $content .= _("New page");
314             $content .= "\n\n";
315             $content .= $wikitext;
316             $editedby = sprintf(_("Created by: %s"), $this->fromId());
317         }
318         $summary = sprintf(_("Summary: %s"), $meta['summary']);
319         $this->sendMail($subject,
320             $editedby . "\n" . $summary . "\n" . $difflink . "\n\n" . $content);
321     }
322
323     /**
324      * Support mass rename / remove (TBD)
325      */
326     function sendPageRenameNotification($to, &$meta)
327     {
328         $pagename = $this->pagename;
329         $editedby = sprintf(_("Renamed by: %s"), $this->fromId());
330         $subject = sprintf(_("Page rename %s to %s"), $pagename, $to);
331         $link = WikiURL($to, true);
332         $this->sendMail($subject,
333             $editedby . "\n" . $link . "\n\n" . "Renamed $pagename to $to");
334     }
335
336     /**
337      * The handlers:
338      */
339     function onChangePage(&$wikidb, &$wikitext, $version, &$meta)
340     {
341         $result = true;
342         if (!isa($GLOBALS['request'], 'MockRequest')) {
343             $notify = $wikidb->get('notify');
344             /* Generate notification emails? */
345             if (!empty($notify) and is_array($notify)) {
346                 if (empty($this->pagename))
347                     $this->pagename = $meta['pagename'];
348                 // TODO: Should be used for ModeratePage and RSS2 Cloud xml-rpc also.
349                 $this->getPageChangeEmails($notify);
350                 if (!empty($this->emails)) {
351                     $result = $this->sendPageChangeNotification($wikitext, $version, $meta);
352                 }
353             }
354         }
355         return $result;
356     }
357
358     function onDeletePage(&$wikidb, $pagename)
359     {
360         $result = true;
361         /* Generate notification emails? */
362         if (!$wikidb->isWikiPage($pagename) and !isa($GLOBALS['request'], 'MockRequest')) {
363             $notify = $wikidb->get('notify');
364             if (!empty($notify) and is_array($notify)) {
365                 //TODO: deferr it (quite a massive load if you remove some pages).
366                 $this->getPageChangeEmails($notify);
367                 if (!empty($this->emails)) {
368                     $subject = sprintf(_("User %s removed page %s"), $this->fromId(), $pagename);
369                     $result = $this->sendMail($subject, $subject . "\n\n");
370                 }
371             }
372         }
373         return $result;
374     }
375
376     function onRenamePage(&$wikidb, $oldpage, $new_pagename)
377     {
378         $result = true;
379         if (!isa($GLOBALS['request'], 'MockRequest')) {
380             $notify = $wikidb->get('notify');
381             if (!empty($notify) and is_array($notify)) {
382                 $this->getPageChangeEmails($notify);
383                 if (!empty($this->emails)) {
384                     $newpage = $wikidb->getPage($new_pagename);
385                     $current = $newpage->getCurrentRevision();
386                     $meta = $current->_data;
387                     $this->pagename = $oldpage;
388                     $result = $this->sendPageRenameNotification($new_pagename, $meta);
389                 }
390             }
391         }
392     }
393
394     /**
395      * Send mail to user and store the cookie in the db
396      * wikiurl?action=ConfirmEmail&id=bla
397      */
398     function sendEmailConfirmation($email, $userid)
399     {
400         $id = rand_ascii_readable(16);
401         $wikidb = $GLOBALS['request']->getDbh();
402         $data = $wikidb->get('ConfirmEmail');
403         while (!empty($data[$id])) { // id collision
404             $id = rand_ascii_readable(16);
405         }
406         $subject = _("E-mail address confirmation");
407         $ip = $request->get('REMOTE_HOST');
408         $expire_date = time() + 7 * 86400;
409         $content = fmt("Someone, probably you from IP address %s, has registered an
410 account \"%s\" with this e-mail address on %s.
411
412 To confirm that this account really does belong to you and activate
413 e-mail features on %s, open this link in your browser:
414
415 %s
416
417 If this is *not* you, don't follow the link. This confirmation code
418 will expire at %s.",
419             $ip, $userid, WIKI_NAME, WIKI_NAME,
420             WikiURL(HOME_PAGE, array('action' => 'ConfirmEmail',
421                     'id' => $id),
422                 true),
423             CTime($expire_date));
424         $this->sendMail($subject, $content, "", true);
425         $data[$id] = array('email' => $email,
426             'userid' => $userid,
427             'expire' => $expire_date);
428         $wikidb->set('ConfirmEmail', $data);
429         return '';
430     }
431
432     function checkEmailConfirmation()
433     {
434         global $request;
435         $wikidb = $request->getDbh();
436         $data = $wikidb->get('ConfirmEmail');
437         $id = $request->getArg('id');
438         if (empty($data[$id])) { // id not found
439             return HTML(HTML::h1("Confirm E-mail address"),
440                 HTML::h1("Sorry! Wrong URL"));
441         }
442         // upgrade the user
443         $userid = $data['userid'];
444         $email = $data['email'];
445         $u = $request->getUser();
446         if ($u->UserName() == $userid) { // lucky: current user (session)
447             $prefs = $u->getPreferences();
448             $request->_user->_level = WIKIAUTH_USER;
449             $request->_prefs->set('emailVerified', true);
450         } else { // not current user
451             if (ENABLE_USER_NEW) {
452                 $u = WikiUser($userid);
453                 $u->getPreferences();
454                 $prefs = &$u->_prefs;
455             } else {
456                 $u = new WikiUser($request, $userid);
457                 $prefs = $u->getPreferences();
458             }
459             $u->_level = WIKIAUTH_USER;
460             $request->setUser($u);
461             $request->_prefs->set('emailVerified', true);
462         }
463         unset($data[$id]);
464         $wikidb->set('ConfirmEmail', $data);
465         return HTML(HTML::h1("Confirm E-mail address"),
466             HTML::p("Your e-mail address has now been confirmed."));
467     }
468
469     function subject_encode($subject)
470     {
471         // We need to encode the subject if it contains non-ASCII characters
472         // The page name may contain non-ASCII characters, as well as
473         // the translation of the messages, e.g. _("PageChange Notification of %s");
474
475         // If all characters are ASCII, do nothing
476         if (isAsciiString($subject)) {
477             return $subject;
478         }
479
480         // Let us try quoted printable first
481         if (function_exists('quoted_printable_encode')) { // PHP 5.3
482             return "=?UTF-8?Q?" . quoted_printable_encode($subject) . "?=";
483         }
484
485         // If not, encode in base64 (less human-readable)
486         return "=?UTF-8?B?" . base64_encode($subject) . "?=";
487     }
488 }
489
490 // Local Variables:
491 // mode: php
492 // tab-width: 8
493 // c-basic-offset: 4
494 // c-hanging-comment-ender-p: nil
495 // indent-tabs-mode: nil
496 // End: