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