3 /* Copyright (C) 2006-2007,2009 Reini Urban
4 * Copyright (C) 2009 Marc-Etienne Vargenau, Alcatel-Lucent
6 * This file is part of PhpWiki.
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.
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.
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.
24 * Handle the pagelist pref[notifyPages] logic for users
25 * and notify => hash ( page => (userid => userhash) ) for pages.
26 * Generate notification emails.
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
39 * ? handle emailed confirmation links (EmailSignup, ModeratedPage)
45 if (!defined("MAILER_LOG")) {
47 define("MAILER_LOG", 'c:/wikimail.log');
49 define("MAILER_LOG", '/var/log/wikimail.log');
56 function MailNotify($pagename)
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();
69 if (defined('FUSIONFORGE') and FUSIONFORGE) {
70 return $request->_user->getId();
72 return $request->_user->getId() . '@' . $request->get('REMOTE_HOST');
79 return $this->userEmail($request->_user->getId(), false);
82 function userEmail($userid, $doverify = true)
86 // Disable verification of emails for corporate env.
87 if (defined('FUSIONFORGE') and FUSIONFORGE) {
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')) {
99 } else { // not current user
100 if (ENABLE_USER_NEW) {
101 $u = WikiUser($userid);
102 $u->getPreferences();
103 $prefs = &$u->_prefs;
105 $u = new WikiUser($request, $userid);
106 $prefs = $u->getPreferences();
108 $email = $prefs->get('email');
109 if ($doverify and !$prefs->get('emailVerified')) {
117 * getPageChangeEmails($notify)
118 * @param $notify: hash ( page => (userid => userhash) )
120 * unique array of ($emails, $userids)
122 function getPageChangeEmails($notify)
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');
135 foreach ($users as $userid => $user) {
137 $usermail = $user['email'];
139 if (($usermail == $curuserprefsemail)
140 and ($ownModifications)
142 // It's my own modification
143 // and I do not want to receive it
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
158 if (!$user) { // handle the case for ModeratePage:
159 // no prefs, just userid's.
160 $emails[] = $this->userEmail($userid, false);
161 $userids[] = $userid;
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);
170 $notify[$page][$userid]['verified'] = 1;
171 $request->_dbi->set('notify', $notify);
173 $userids[] = $userid;
180 $this->emails = array_unique($emails);
181 $this->userids = array_unique($userids);
182 return array($this->emails, $this->userids);
185 function sendMail($subject,
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)) {
200 $notice = _("PageChange Notification of %s");
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=" . CHARSET . "; format=flowed\r\n" .
207 "Content-Transfer-Encoding: 8bit";
209 $ok = mail(($to = array_shift($emails)),
211 $subject . "\n" . $content,
214 if (MAILER_LOG and is_writable(MAILER_LOG)) {
215 global $ErrorManager;
217 $f = fopen(MAILER_LOG, "a");
218 fwrite($f, "\n\nX-MailSentOK: " . $ok ? 'OK' : 'FAILED');
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);
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);
239 trigger_error(sprintf($notice, $this->pagename)
241 . sprintf(_("sent to %s"), join(',', $this->userids)),
245 trigger_error(sprintf($notice, $this->pagename)
247 . sprintf(_("Error: Couldn't send %s to %s"),
248 $subject . "\n" . $content, join(',', $this->userids)),
255 * Send udiff for a changed page to multiple users.
256 * See rename and remove methods also
258 function sendPageChangeNotification(&$wikitext, $version, &$meta)
263 if (isset($request->_deferredPageChangeNotification)) {
264 // collapse multiple changes (loaddir) into one email
265 $request->_deferredPageChangeNotification[] =
266 array($this->pagename, $this->emails, $this->userids);
269 $backend = &$request->_dbi->_backend;
270 $previous = $backend->get_previous_version($this->pagename, $version);
271 if (!isset($meta['mtime'])) {
272 $meta['mtime'] = time();
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);
284 $other_content = explode("\n", $prevdata['%content']);
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());
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");
305 $content .= $wikitext;
306 $editedby = sprintf(_("Created by: %s"), $this->fromId());
308 $summary = sprintf(_("Summary: %s"), $meta['summary']);
309 $this->sendMail($subject,
310 $editedby . "\n" . $summary . "\n" . $difflink . "\n\n" . $content);
314 * Support mass rename / remove (TBD)
316 function sendPageRenameNotification($to)
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");
329 function onChangePage(&$wikidb, &$wikitext, $version, &$meta)
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);
346 function onDeletePage(&$wikidb, $pagename)
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");
364 function onRenamePage(&$wikidb, $oldpage, $new_pagename)
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);
379 * Send mail to user and store the cookie in the db
380 * wikiurl?action=ConfirmEmail&id=bla
382 function sendEmailConfirmation($email, $userid)
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);
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.
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:
402 If this is *not* you, don't follow the link. This confirmation code
404 $ip, $userid, WIKI_NAME, WIKI_NAME,
405 WikiURL(HOME_PAGE, array('action' => 'ConfirmEmail',
408 CTime($expire_date));
409 $this->sendMail($subject, $content, "", true);
410 $data[$id] = array('email' => $email,
412 'expire' => $expire_date);
413 $wikidb->set('ConfirmEmail', $data);
417 function checkEmailConfirmation()
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"));
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();
438 $u = new WikiUser($request, $userid);
440 $u->_level = WIKIAUTH_USER;
441 $request->setUser($u);
442 $request->_prefs->set('emailVerified', true);
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."));
450 function subject_encode($subject)
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");
456 // If all characters are ASCII, do nothing
457 if (isAsciiString($subject)) {
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)) . "?=";
467 // If not, encode in base64 (less human-readable)
468 return "=?UTF-8?B?" . base64_encode($subject) . "?=";
476 // c-hanging-comment-ender-p: nil
477 // indent-tabs-mode: nil