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 $u = WikiUser($userid);
101 $u->getPreferences();
102 $prefs = &$u->_prefs;
103 $email = $prefs->get('email');
104 if ($doverify and !$prefs->get('emailVerified')) {
112 * getPageChangeEmails($notify)
113 * @param $notify: hash ( page => (userid => userhash) )
115 * unique array of ($emails, $userids)
117 function getPageChangeEmails($notify)
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');
130 foreach ($users as $userid => $user) {
132 $usermail = $user['email'];
134 if (($usermail == $curuserprefsemail)
135 and ($ownModifications)
137 // It's my own modification
138 // and I do not want to receive it
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
153 if (!$user) { // handle the case for ModeratePage:
154 // no prefs, just userid's.
155 $emails[] = $this->userEmail($userid, false);
156 $userids[] = $userid;
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);
165 $notify[$page][$userid]['verified'] = 1;
166 $request->_dbi->set('notify', $notify);
168 $userids[] = $userid;
175 $this->emails = array_unique($emails);
176 $this->userids = array_unique($userids);
177 return array($this->emails, $this->userids);
180 function sendMail($subject,
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)) {
195 $notice = _("PageChange Notification of %s");
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";
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)
258 if (isset($request->_deferredPageChangeNotification)) {
259 // collapse multiple changes (loaddir) into one email
260 $request->_deferredPageChangeNotification[] =
261 array($this->pagename, $this->emails, $this->userids);
264 $backend = &$request->_dbi->_backend;
265 $previous = $backend->get_previous_version($this->pagename, $version);
266 if (!isset($meta['mtime'])) {
267 $meta['mtime'] = time();
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);
279 $other_content = explode("\n", $prevdata['%content']);
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());
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");
300 $content .= $wikitext;
301 $editedby = sprintf(_("Created by: %s"), $this->fromId());
303 $summary = sprintf(_("Summary: %s"), $meta['summary']);
304 $this->sendMail($subject,
305 $editedby . "\n" . $summary . "\n" . $difflink . "\n\n" . $content);
309 * Support mass rename / remove (TBD)
311 function sendPageRenameNotification($to)
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");
324 function onChangePage(&$wikidb, &$wikitext, $version, &$meta)
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);
341 function onDeletePage(&$wikidb, $pagename)
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");
359 function onRenamePage(&$wikidb, $oldpage, $new_pagename)
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);
374 * Send mail to user and store the cookie in the db
375 * wikiurl?action=ConfirmEmail&id=bla
377 function sendEmailConfirmation($email, $userid)
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);
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.
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:
397 If this is *not* you, don't follow the link. This confirmation code
399 $ip, $userid, WIKI_NAME, WIKI_NAME,
400 WikiURL(HOME_PAGE, array('action' => 'ConfirmEmail',
403 CTime($expire_date));
404 $this->sendMail($subject, $content, "", true);
405 $data[$id] = array('email' => $email,
407 'expire' => $expire_date);
408 $wikidb->set('ConfirmEmail', $data);
412 function checkEmailConfirmation()
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"));
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);
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."));
441 function subject_encode($subject)
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");
447 // If all characters are ASCII, do nothing
448 if (isAsciiString($subject)) {
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)) . "?=";
458 // If not, encode in base64 (less human-readable)
459 return "=?UTF-8?B?" . base64_encode($subject) . "?=";
467 // c-hanging-comment-ender-p: nil
468 // indent-tabs-mode: nil