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');
55 function MailNotify($pagename) {
56 $this->pagename = $pagename; /* which page */
57 $this->emails = array(); /* to which addresses */
58 $this->userids = array(); /* corresponding array of displayed names,
59 don't display the email addresses */
60 /* From: from whom the mail appears to be */
61 $this->from = $this->fromId();
67 return $request->_user->getId();
69 return $request->_user->getId() . '@' . $request->get('REMOTE_HOST');
73 function userEmail($userid, $doverify = true) {
76 // Disable verification of emails for corporate env.
81 $u = $request->getUser();
82 if ($u->UserName() == $userid) { // lucky: current user
83 $prefs = $u->getPreferences();
84 $email = $prefs->get('email');
85 // do a dynamic emailVerified check update
86 if ($doverify and !$request->_prefs->get('emailVerified')) {
89 } else { // not current user
90 if (ENABLE_USER_NEW) {
91 $u = WikiUser($userid);
95 $u = new WikiUser($request, $userid);
96 $prefs = $u->getPreferences();
98 $email = $prefs->get('email');
99 if ($doverify and !$prefs->get('emailVerified')) {
107 * getPageChangeEmails($notify)
108 * @param $notify: hash ( page => (userid => userhash) )
110 * unique array of ($emails, $userids)
112 function getPageChangeEmails($notify) {
114 $emails = array(); $userids = array();
115 foreach ($notify as $page => $users) {
116 if (glob_match($page, $this->pagename)) {
119 $curuser = $request->getUser();
120 $curusername = $curuser->UserName();
121 $curuserprefs = $curuser->getPreferences();
122 $curuserprefsemail = $curuserprefs->get('email');
123 $ownModifications = $curuserprefs->get('ownModifications');
124 $majorModificationsOnly = $curuserprefs->get('majorModificationsOnly');
126 foreach ($users as $userid => $user) {
128 $usermail = $user['email'];
130 if (($usermail == $curuserprefsemail)
131 and ($ownModifications)) {
132 // It's my own modification
133 // and I do not want to receive it
137 if ($majorModificationsOnly) {
138 $backend = &$request->_dbi->_backend;
139 $version = $backend->get_latest_version($this->pagename);
140 $versiondata = $backend->get_versiondata($this->pagename, $version, true);
141 if ($versiondata['is_minor_edit']) {
142 // It's a minor modification
143 // and I do not want to receive it
148 if (!$user) { // handle the case for ModeratePage:
149 // no prefs, just userid's.
150 $emails[] = $this->userEmail($userid, false);
151 $userids[] = $userid;
153 if (!empty($user['verified']) and !empty($user['email'])) {
154 $emails[] = $user['email'];
155 $userids[] = $userid;
156 } elseif (!empty($user['email'])) {
157 // do a dynamic emailVerified check update
158 $email = $this->userEmail($userid, true);
160 $notify[$page][$userid]['verified'] = 1;
161 $request->_dbi->set('notify', $notify);
163 $userids[] = $userid;
166 // ignore verification
169 if (!in_array($user['email'], $emails))
170 $emails[] = $user['email'];
177 $this->emails = array_unique($emails);
178 $this->userids = array_unique($userids);
179 return array($this->emails, $this->userids);
182 function sendMail($subject,
187 // Add WIKI_NAME to Subject
188 $subject = "[".WIKI_NAME."] ".$subject;
189 // Encode $subject if needed
190 $encoded_subject = $this->subject_encode($subject);
191 $emails = $this->emails;
193 // Do not send if modification is from FusionForge admin
194 if (FUSIONFORGE and $from == ADMIN_USER) {
197 if (!$notice) $notice = _("PageChange Notification of %s");
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=".CHARSET."; format=flowed\r\n" .
202 "Content-Transfer-Encoding: 8bit";
204 $ok = mail(($to = array_shift($emails)),
206 $subject."\n".$content,
209 if (MAILER_LOG and is_writable(MAILER_LOG)) {
210 global $ErrorManager;
212 $f = fopen(MAILER_LOG, "a");
213 fwrite($f, "\n\nX-MailSentOK: " . $ok ? 'OK' : 'FAILED');
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);
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);
234 trigger_error(sprintf($notice, $this->pagename)
236 . sprintf(_("sent to %s"), join(',',$this->userids)),
240 trigger_error(sprintf($notice, $this->pagename)
242 . sprintf(_("Error: Couldn't send %s to %s"),
243 $subject."\n".$content, join(',',$this->userids)),
250 * Send udiff for a changed page to multiple users.
251 * See rename and remove methods also
253 function sendPageChangeNotification(&$wikitext, $version, &$meta) {
257 if (isset($request->_deferredPageChangeNotification)) {
258 // collapse multiple changes (loaddir) into one email
259 $request->_deferredPageChangeNotification[] =
260 array($this->pagename, $this->emails, $this->userids);
263 $backend = &$request->_dbi->_backend;
264 $subject = _("Page change").' '.($this->pagename);
265 $previous = $backend->get_previous_version($this->pagename, $version);
266 if (!isset($meta['mtime'])) {
267 $meta['mtime'] = time();
270 $difflink = WikiURL($this->pagename, array('action'=>'diff'), true);
271 $cache = &$request->_dbi->_cache;
272 $this_content = explode("\n", $wikitext);
273 $prevdata = $cache->get_versiondata($this->pagename, $previous, true);
274 if (empty($prevdata['%content']))
275 $prevdata = $backend->get_versiondata($this->pagename, $previous, true);
276 $other_content = explode("\n", $prevdata['%content']);
278 include_once("lib/difflib.php");
279 $diff2 = new Diff($other_content, $this_content);
280 //$context_lines = max(4, count($other_content) + 1,
281 // count($this_content) + 1);
282 $fmt = new UnifiedDiffFormatter(/*$context_lines*/);
283 $content = $this->pagename . " " . $previous . " " .
284 Iso8601DateTime($prevdata['mtime']) . "\n";
285 $content .= $this->pagename . " " . $version . " " .
286 Iso8601DateTime($meta['mtime']) . "\n";
287 $content .= $fmt->format($diff2);
290 $difflink = WikiURL($this->pagename,array(),true);
291 $content = $this->pagename . " " . $version . " " .
292 Iso8601DateTime($meta['mtime']) . "\n";
293 $content .= _("New page");
295 $content .= $wikitext;
297 $editedby = sprintf(_("Edited by: %s"), $this->from);
298 $summary = sprintf(_("Summary: %s"), $meta['summary']);
299 $this->sendMail($subject,
300 $editedby."\n".$summary."\n".$difflink."\n\n".$content);
304 * Support mass rename / remove (not yet tested)
306 function sendPageRenameNotification ($to, &$meta) {
309 if (@is_array($request->_deferredPageRenameNotification)) {
310 $request->_deferredPageRenameNotification[] =
311 array($this->pagename, $to, $meta, $this->emails, $this->userids);
313 $pagename = $this->pagename;
314 $editedby = sprintf(_("Edited by: %s"), $this->from);
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");
325 function onChangePage (&$wikidb, &$wikitext, $version, &$meta) {
327 if (!isa($GLOBALS['request'],'MockRequest')) {
328 $notify = $wikidb->get('notify');
329 /* Generate notification emails? */
330 if (!empty($notify) and is_array($notify)) {
331 if (empty($this->pagename))
332 $this->pagename = $meta['pagename'];
333 // TODO: Should be used for ModeratePage and RSS2 Cloud xml-rpc also.
334 $this->getPageChangeEmails($notify);
335 if (!empty($this->emails)) {
336 $result = $this->sendPageChangeNotification($wikitext, $version, $meta);
343 function onDeletePage (&$wikidb, $pagename) {
345 /* Generate notification emails? */
346 if (! $wikidb->isWikiPage($pagename) and !isa($GLOBALS['request'],'MockRequest')) {
347 $notify = $wikidb->get('notify');
348 if (!empty($notify) and is_array($notify)) {
349 //TODO: deferr it (quite a massive load if you remove some pages).
350 $this->getPageChangeEmails($notify);
351 if (!empty($this->emails)) {
352 $subject = sprintf(_("User %s removed page %s"), $this->from, $pagename);
353 $result = $this->sendMail($subject, $subject."\n\n");
360 function onRenamePage (&$wikidb, $oldpage, $new_pagename) {
362 if (!isa($GLOBALS['request'], 'MockRequest')) {
363 $notify = $wikidb->get('notify');
364 if (!empty($notify) and is_array($notify)) {
365 $this->getPageChangeEmails($notify);
366 if (!empty($this->emails)) {
367 $newpage = $wikidb->getPage($new_pagename);
368 $current = $newpage->getCurrentRevision();
369 $meta = $current->_data;
370 $this->pagename = $oldpage;
371 $result = $this->sendPageRenameNotification($new_pagename, $meta);
378 * Send mail to user and store the cookie in the db
379 * wikiurl?action=ConfirmEmail&id=bla
381 function sendEmailConfirmation ($email, $userid) {
382 $id = rand_ascii_readable(16);
383 $wikidb = $GLOBALS['request']->getDbh();
384 $data = $wikidb->get('ConfirmEmail');
385 while(!empty($data[$id])) { // id collision
386 $id = rand_ascii_readable(16);
388 $subject = _("E-mail address confirmation");
389 $ip = $request->get('REMOTE_HOST');
390 $expire_date = time() + 7*86400;
391 $content = fmt("Someone, probably you from IP address %s, has registered an
392 account \"%s\" with this e-mail address on %s.
394 To confirm that this account really does belong to you and activate
395 e-mail features on %s, open this link in your browser:
399 If this is *not* you, don't follow the link. This confirmation code
401 $ip, $userid, WIKI_NAME, WIKI_NAME,
402 WikiURL(HOME_PAGE, array('action' => 'ConfirmEmail',
405 CTime($expire_date));
406 $this->sendMail($subject, $content, "", true);
407 $data[$id] = array('email' => $email,
409 'expire' => $expire_date);
410 $wikidb->set('ConfirmEmail', $data);
414 function checkEmailConfirmation () {
416 $wikidb = $request->getDbh();
417 $data = $wikidb->get('ConfirmEmail');
418 $id = $request->getArg('id');
419 if (empty($data[$id])) { // id not found
420 return HTML(HTML::h1("Confirm E-mail address"),
421 HTML::h1("Sorry! Wrong URL"));
424 $userid = $data['userid'];
425 $email = $data['email'];
426 $u = $request->getUser();
427 if ($u->UserName() == $userid) { // lucky: current user (session)
428 $prefs = $u->getPreferences();
429 $request->_user->_level = WIKIAUTH_USER;
430 $request->_prefs->set('emailVerified', true);
431 } else { // not current user
432 if (ENABLE_USER_NEW) {
433 $u = WikiUser($userid);
434 $u->getPreferences();
435 $prefs = &$u->_prefs;
437 $u = new WikiUser($request, $userid);
438 $prefs = $u->getPreferences();
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) {
451 // We need to encode the subject if it contains non-ASCII characters
452 // The page name may contain non-ASCII characters, as well as
453 // the translation of the messages, e.g. _("PageChange Notification of %s");
455 // If all characters are ASCII, do nothing
456 if (isAsciiString($subject)) {
460 // Let us try quoted printable first
461 if (function_exists('quoted_printable_encode')) { // PHP 5.3
462 return "=?UTF-8?Q?".quoted_printable_encode($subject)."?=";
465 // If not, encode in base64 (less human-readable)
466 return "=?UTF-8?B?".base64_encode($subject)."?=";
474 // c-hanging-comment-ender-p: nil
475 // indent-tabs-mode: nil