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);
277 $other_content = explode("\n", $prevdata['%content']);
279 include_once("lib/difflib.php");
280 $diff2 = new Diff($other_content, $this_content);
281 //$context_lines = max(4, count($other_content) + 1,
282 // count($this_content) + 1);
283 $fmt = new UnifiedDiffFormatter(/*$context_lines*/);
284 $content = $this->pagename . " " . $previous . " " .
285 Iso8601DateTime($prevdata['mtime']) . "\n";
286 $content .= $this->pagename . " " . $version . " " .
287 Iso8601DateTime($meta['mtime']) . "\n";
288 $content .= $fmt->format($diff2);
291 $difflink = WikiURL($this->pagename,array(),true);
292 $content = $this->pagename . " " . $version . " " .
293 Iso8601DateTime($meta['mtime']) . "\n";
294 $content .= _("New page");
296 $content .= $wikitext;
298 $editedby = sprintf(_("Edited by: %s"), $this->from);
299 $summary = sprintf(_("Summary: %s"), $meta['summary']);
300 $this->sendMail($subject,
301 $editedby."\n".$summary."\n".$difflink."\n\n".$content);
305 * Support mass rename / remove (TBD)
307 function sendPageRenameNotification ($to, &$meta) {
308 $pagename = $this->pagename;
309 $editedby = sprintf(_("Renamed by: %s"), $this->fromId());
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");
319 function onChangePage (&$wikidb, &$wikitext, $version, &$meta) {
321 if (!isa($GLOBALS['request'],'MockRequest')) {
322 $notify = $wikidb->get('notify');
323 /* Generate notification emails? */
324 if (!empty($notify) and is_array($notify)) {
325 if (empty($this->pagename))
326 $this->pagename = $meta['pagename'];
327 // TODO: Should be used for ModeratePage and RSS2 Cloud xml-rpc also.
328 $this->getPageChangeEmails($notify);
329 if (!empty($this->emails)) {
330 $result = $this->sendPageChangeNotification($wikitext, $version, $meta);
337 function onDeletePage (&$wikidb, $pagename) {
339 /* Generate notification emails? */
340 if (! $wikidb->isWikiPage($pagename) and !isa($GLOBALS['request'],'MockRequest')) {
341 $notify = $wikidb->get('notify');
342 if (!empty($notify) and is_array($notify)) {
343 //TODO: deferr it (quite a massive load if you remove some pages).
344 $this->getPageChangeEmails($notify);
345 if (!empty($this->emails)) {
346 $subject = sprintf(_("User %s removed page %s"), $this->from, $pagename);
347 $result = $this->sendMail($subject, $subject."\n\n");
354 function onRenamePage (&$wikidb, $oldpage, $new_pagename) {
356 if (!isa($GLOBALS['request'], 'MockRequest')) {
357 $notify = $wikidb->get('notify');
358 if (!empty($notify) and is_array($notify)) {
359 $this->getPageChangeEmails($notify);
360 if (!empty($this->emails)) {
361 $newpage = $wikidb->getPage($new_pagename);
362 $current = $newpage->getCurrentRevision();
363 $meta = $current->_data;
364 $this->pagename = $oldpage;
365 $result = $this->sendPageRenameNotification($new_pagename, $meta);
372 * Send mail to user and store the cookie in the db
373 * wikiurl?action=ConfirmEmail&id=bla
375 function sendEmailConfirmation ($email, $userid) {
376 $id = rand_ascii_readable(16);
377 $wikidb = $GLOBALS['request']->getDbh();
378 $data = $wikidb->get('ConfirmEmail');
379 while(!empty($data[$id])) { // id collision
380 $id = rand_ascii_readable(16);
382 $subject = _("E-mail address confirmation");
383 $ip = $request->get('REMOTE_HOST');
384 $expire_date = time() + 7*86400;
385 $content = fmt("Someone, probably you from IP address %s, has registered an
386 account \"%s\" with this e-mail address on %s.
388 To confirm that this account really does belong to you and activate
389 e-mail features on %s, open this link in your browser:
393 If this is *not* you, don't follow the link. This confirmation code
395 $ip, $userid, WIKI_NAME, WIKI_NAME,
396 WikiURL(HOME_PAGE, array('action' => 'ConfirmEmail',
399 CTime($expire_date));
400 $this->sendMail($subject, $content, "", true);
401 $data[$id] = array('email' => $email,
403 'expire' => $expire_date);
404 $wikidb->set('ConfirmEmail', $data);
408 function checkEmailConfirmation () {
410 $wikidb = $request->getDbh();
411 $data = $wikidb->get('ConfirmEmail');
412 $id = $request->getArg('id');
413 if (empty($data[$id])) { // id not found
414 return HTML(HTML::h1("Confirm E-mail address"),
415 HTML::h1("Sorry! Wrong URL"));
418 $userid = $data['userid'];
419 $email = $data['email'];
420 $u = $request->getUser();
421 if ($u->UserName() == $userid) { // lucky: current user (session)
422 $prefs = $u->getPreferences();
423 $request->_user->_level = WIKIAUTH_USER;
424 $request->_prefs->set('emailVerified', true);
425 } else { // not current user
426 if (ENABLE_USER_NEW) {
427 $u = WikiUser($userid);
428 $u->getPreferences();
429 $prefs = &$u->_prefs;
431 $u = new WikiUser($request, $userid);
432 $prefs = $u->getPreferences();
434 $u->_level = WIKIAUTH_USER;
435 $request->setUser($u);
436 $request->_prefs->set('emailVerified', true);
439 $wikidb->set('ConfirmEmail', $data);
440 return HTML(HTML::h1("Confirm E-mail address"),
441 HTML::p("Your e-mail address has now been confirmed."));
444 function subject_encode ($subject) {
445 // We need to encode the subject if it contains non-ASCII characters
446 // The page name may contain non-ASCII characters, as well as
447 // the translation of the messages, e.g. _("PageChange Notification of %s");
449 // If all characters are ASCII, do nothing
450 if (isAsciiString($subject)) {
454 // Let us try quoted printable first
455 if (function_exists('quoted_printable_encode')) { // PHP 5.3
456 return "=?UTF-8?Q?".quoted_printable_encode($subject)."?=";
459 // If not, encode in base64 (less human-readable)
460 return "=?UTF-8?B?".base64_encode($subject)."?=";
468 // c-hanging-comment-ender-p: nil
469 // indent-tabs-mode: nil