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