]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/MailNotify.php
Activated Id substitution for Subversion
[SourceForge/phpwiki.git] / lib / MailNotify.php
1 <?php //-*-php-*-
2 rcs_id('$Id$');
3
4 /**
5  * Handle the pagelist pref[notifyPages] logic for users
6  * and notify => hash ( page => (userid => userhash) ) for pages.
7  * Generate notification emails.
8  *
9  * We add WikiDB handlers and register ourself there:
10  *   onChangePage, onDeletePage, onRenamePage
11  * Administrative actions:
12  *   [Watch] WatchPage - add a page, or delete watch handlers into the users 
13  *                       pref[notifyPages] slot.
14  *   My WatchList      - view or edit list/regex of pref[notifyPages].
15  *   EMailConfirm methods: send and verify
16  *
17  * Helper functions:
18  *   getPageChangeEmails
19  *   MailAdmin
20  *   ? handle emailed confirmation links (EmailSignup, ModeratedPage)
21  *
22  * @package MailNotify
23  * @author  Reini Urban
24  */
25
26 if (!defined("MAILER_LOG"))
27     if (isWindows())
28         define("MAILER_LOG", 'c:/wikimail.log');
29     else
30         define("MAILER_LOG", '/var/log/wikimail.log');
31
32 class MailNotify {
33
34     function MailNotify($pagename) {
35         $this->pagename = $pagename; /* which page */
36         $this->emails  = array();    /* to which addresses */
37         $this->userids = array();    /* corresponding array of displayed names, 
38                                         don't display the email addresses */
39         /* From: from whom the mail appears to be */
40         $this->from = $this->fromId();
41     }
42
43     function fromId() {
44         global $request;
45         return $request->_user->getId() . '@' .  $request->get('REMOTE_HOST');
46     }
47
48     function userEmail($userid, $doverify = true) {
49         global $request;
50         $u = $request->getUser();
51         if ($u->UserName() == $userid) { // lucky: current user
52             $prefs = $u->getPreferences();
53             $email = $prefs->get('email');
54             // do a dynamic emailVerified check update
55             if ($doverify and !$request->_prefs->get('emailVerified'))
56                 $email = '';
57         } else {  // not current user
58             if (ENABLE_USER_NEW) {
59                 $u = WikiUser($userid);
60                 $u->getPreferences();
61                 $prefs = &$u->_prefs;
62             } else {
63                 $u = new WikiUser($request, $userid);
64                 $prefs = $u->getPreferences();
65             }
66             $email = $prefs->get('email');
67             if ($doverify and !$prefs->get('emailVerified')) {
68                 $email = '';
69             }
70         }
71         return $email;
72     }
73
74     /**
75      * getPageChangeEmails($notify)
76      * @param  $notify: hash ( page => (userid => userhash) )
77      * @return array
78      *         unique array of ($emails, $userids)
79      */
80     function getPageChangeEmails($notify) {
81         global $request;
82         $emails = array(); $userids = array();
83         foreach ($notify as $page => $users) {
84             if (glob_match($page, $this->pagename)) {
85                 foreach ($users as $userid => $user) {
86                     if (!$user) { // handle the case for ModeratePage: 
87                                   // no prefs, just userid's.
88                         $emails[] = $this->userEmail($userid, false);
89                         $userids[] = $userid;
90                     } else {
91                         if (!empty($user['verified']) and !empty($user['email'])) {
92                             $emails[]  = $user['email'];
93                             $userids[] = $userid;
94                         } elseif (!empty($user['email'])) {
95                             // do a dynamic emailVerified check update
96                             $email = $this->userEmail($userid, true);
97                             if ($email) {
98                                 $notify[$page][$userid]['verified'] = 1;
99                                 $request->_dbi->set('notify', $notify);
100                                 $emails[] = $email;
101                                 $userids[] = $userid;
102                             }
103                         }
104                         // ignore verification
105                         /*
106                         if (DEBUG) {
107                             if (!in_array($user['email'], $emails))
108                                 $emails[] = $user['email'];
109                         }
110                         */
111                     }
112                 }
113             }
114         }
115         $this->emails = array_unique($emails);
116         $this->userids = array_unique($userids);
117         return array($this->emails, $this->userids);
118     }
119     
120     function sendMail($subject, $content, 
121                       $notice = false,
122                       $silent = 0)
123     {
124         global $request;
125         if (!DEBUG and $silent === 0)
126             $silent = true;
127         $emails = $this->emails;
128         $from = $this->from;
129         if (!$notice) $notice = _("PageChange Notification of %s");
130         $ok = mail(($to = array_shift($emails)),
131                  "[".WIKI_NAME."] ".$subject, 
132                    $subject."\n".$content,
133                    "From: $from\r\nBcc: ".join(',', $emails)
134                    );
135         if (MAILER_LOG and is_writable(MAILER_LOG)) {
136             $f = fopen(MAILER_LOG, "a");
137             fwrite($f, "\n\nX-MailSentOK: " . $ok ? 'OK' : 'FAILED');
138             if (!$ok) {
139                 global $ErrorManager;
140                 // get last error message
141                 $last_err = $ErrorManager->_postponed_errors[count($ErrorHandler->_postponed_errors)-1];
142                 fwrite($f, "\nX-MailFailure: " . $last_err);
143             }
144             fwrite($f, "\nDate: " . CTime());
145             fwrite($f, "\nSubject: $subject");
146             fwrite($f, "\nFrom: $from");
147             fwrite($f, "\nTo: $to");
148             fwrite($f, "\nBcc: ".join(',', $emails));
149             fwrite($f, "\n\n". $content);
150             fclose($f);
151         }
152         if ($ok) {
153             if (!$silent)
154                 trigger_error(sprintf($notice, $this->pagename)
155                               . " "
156                               . sprintf(_("sent to %s"), join(',',$this->userids)),
157                               E_USER_NOTICE);
158             return true;
159         } else {
160             trigger_error(sprintf($notice, $this->pagename)
161                           . " "
162                           . sprintf(_("Error: Couldn't send %s to %s"), 
163                                    $subject."\n".$content, join(',',$this->userids)), 
164                           E_USER_WARNING);
165             return false;
166         }
167     }
168     
169     /**
170      * Send udiff for a changed page to multiple users.
171      * See rename and remove methods also
172      */
173     function sendPageChangeNotification(&$wikitext, $version, &$meta) {
174
175         global $request;
176
177         if (@is_array($request->_deferredPageChangeNotification)) {
178             // collapse multiple changes (loaddir) into one email
179             $request->_deferredPageChangeNotification[] = 
180                 array($this->pagename, $this->emails, $this->userids);
181             return;
182         }
183         $backend = &$request->_dbi->_backend;
184         $subject = _("Page change").' '.urlencode($this->pagename);
185         $previous = $backend->get_previous_version($this->pagename, $version);
186         if (!isset($meta['mtime'])) $meta['mtime'] = time();
187         if ($previous) {
188             $difflink = WikiURL($this->pagename, array('action'=>'diff'), true);
189             $cache = &$request->_dbi->_cache;
190             $this_content = explode("\n", $wikitext);
191             $prevdata = $cache->get_versiondata($this->pagename, $previous, true);
192             if (empty($prevdata['%content']))
193                 $prevdata = $backend->get_versiondata($this->pagename, $previous, true);
194             $other_content = explode("\n", $prevdata['%content']);
195             
196             include_once("lib/difflib.php");
197             $diff2 = new Diff($other_content, $this_content);
198             //$context_lines = max(4, count($other_content) + 1,
199             //                     count($this_content) + 1);
200             $fmt = new UnifiedDiffFormatter(/*$context_lines*/);
201             $content  = $this->pagename . " " . $previous . " " . 
202                 Iso8601DateTime($prevdata['mtime']) . "\n";
203             $content .= $this->pagename . " " . $version . " " .  
204                 Iso8601DateTime($meta['mtime']) . "\n";
205             $content .= $fmt->format($diff2);
206             
207         } else {
208             $difflink = WikiURL($this->pagename,array(),true);
209             $content = $this->pagename . " " . $version . " " .  
210                 Iso8601DateTime($meta['mtime']) . "\n";
211             $content .= _("New page");
212         }
213         $editedby = sprintf(_("Edited by: %s"), $this->from);
214         //$editedby = sprintf(_("Edited by: %s"), $meta['author']);
215         $this->sendMail($subject, 
216                         $editedby."\n".$difflink."\n\n".$content);
217     }
218
219     /** 
220      * Support mass rename / remove (not yet tested)
221      */
222     function sendPageRenameNotification ($to, &$meta) {
223         global $request;
224
225         if (@is_array($request->_deferredPageRenameNotification)) {
226             $request->_deferredPageRenameNotification[] = 
227                 array($this->pagename, $to, $meta, $this->emails, $this->userids);
228         } else {
229             $pagename = $this->pagename;
230             //$editedby = sprintf(_("Edited by: %s"), $meta['author']) . ' ' . $meta['author_id'];
231             $editedby = sprintf(_("Edited by: %s"), $this->from);
232             $subject = sprintf(_("Page rename %s to %s"), urlencode($pagename), urlencode($to));
233             $link = WikiURL($to, true);
234             $this->sendMail($subject, 
235                             $editedby."\n".$link."\n\n"."Renamed $pagename to $to");
236         }
237     }
238
239     /**
240      * The handlers:
241      */
242     function onChangePage (&$wikidb, &$wikitext, $version, &$meta) {
243         $result = true;
244         if (!isa($GLOBALS['request'],'MockRequest')) {
245             $notify = $wikidb->get('notify');
246             /* Generate notification emails? */
247             if (!empty($notify) and is_array($notify)) {
248                 if (empty($this->pagename))
249                     $this->pagename = $meta['pagename'];
250                 // TODO: Should be used for ModeratePage and RSS2 Cloud xml-rpc also.
251                 $this->getPageChangeEmails($notify);
252                 if (!empty($this->emails)) {
253                     $result = $this->sendPageChangeNotification($wikitext, $version, $meta);
254                 }
255             }
256         }
257         return $result;
258     }
259
260     function onDeletePage (&$wikidb, $pagename) {
261         $result = true;
262         /* Generate notification emails? */
263         if (! $wikidb->isWikiPage($pagename) and !isa($GLOBALS['request'],'MockRequest')) {
264             $notify = $wikidb->get('notify');
265             if (!empty($notify) and is_array($notify)) {
266                 //TODO: deferr it (quite a massive load if you remove some pages).
267                 $this->getPageChangeEmails($notify);
268                 if (!empty($this->emails)) {
269                     $editedby = sprintf(_("Removed by: %s"), $this->from); // Todo: host_id
270                     //$emails = join(',', $this->emails);
271                     $subject = sprintf(_("Page removed %s"), urlencode($pagename));
272                     $page = $wikidb->getPage($pagename);
273                     $rev = $page->getCurrentRevision(true);
274                     $content = $rev->getPackedContent();
275                     $result = $this->sendMail($subject, 
276                                               $editedby."\n"."Deleted $pagename"."\n\n".$content);
277                 }
278             }
279         }
280         //How to create a RecentChanges entry with explaining summary? Dynamically
281         /*
282           $page = $this->getPage($pagename);
283           $current = $page->getCurrentRevision();
284           $meta = $current->_data;
285           $version = $current->getVersion();
286           $meta['summary'] = _("removed");
287           $page->save($current->getPackedContent(), $version + 1, $meta);
288         */
289         return $result;
290     }
291
292     function onRenamePage (&$wikidb, $oldpage, $new_pagename) {
293         $result = true;
294         if (!isa($GLOBALS['request'], 'MockRequest')) {
295             $notify = $wikidb->get('notify');
296             if (!empty($notify) and is_array($notify)) {
297                 $this->getPageChangeEmails($notify);
298                 if (!empty($this->emails)) {
299                     $newpage = $wikidb->getPage($new_pagename);
300                     $current = $newpage->getCurrentRevision();
301                     $meta = $current->_data;
302                     $this->pagename = $oldpage;
303                     $result = $this->sendPageRenameNotification($new_pagename, $meta);
304                 }
305             }
306         }
307     }
308
309     /**
310      * Send mail to user and store the cookie in the db
311      * wikiurl?action=ConfirmEmail&id=bla
312      */
313     function sendEmailConfirmation ($email, $userid) {
314         $id = rand_ascii_readable(16);
315         $wikidb = $GLOBALS['request']->getDbh();
316         $data = $wikidb->get('ConfirmEmail');
317         while(!empty($data[$id])) { // id collision
318             $id = rand_ascii_readable(16);
319         }
320         $subject = WIKI_NAME . " " . _("e-mail address confirmation");
321         $ip = $request->get('REMOTE_HOST');
322         $expire_date = time() + 7*86400;
323         $content = fmt("Someone, probably you from IP address %s, has registered an
324 account \"%s\" with this e-mail address on %s.
325
326 To confirm that this account really does belong to you and activate
327 e-mail features on %s, open this link in your browser:
328
329 %s
330
331 If this is *not* you, don't follow the link. This confirmation code
332 will expire at %s.", 
333                        $ip, $userid, WIKI_NAME, WIKI_NAME, 
334                        WikiURL(HOME_PAGE, array('action' => 'ConfirmEmail',
335                                                 'id' => $id), 
336                                true),
337                        CTime($expire_date));
338         $this->sendMail($subject, $content, "", true);
339         $data[$id] = array('email' => $email,
340                            'userid' => $userid,
341                            'expire' => $expire_date);
342         $wikidb->set('ConfirmEmail', $data);
343         return '';
344     }
345
346     function checkEmailConfirmation () {
347         global $request;
348         $wikidb = $request->getDbh();
349         $data = $wikidb->get('ConfirmEmail');
350         $id = $request->getArg('id');
351         if (empty($data[$id])) { // id not found
352             return HTML(HTML::h1("Confirm E-mail address"),
353                         HTML::h1("Sorry! Wrong URL"));
354         }
355         // upgrade the user
356         $userid = $data['userid'];
357         $email = $data['email'];
358         $u = $request->getUser();
359         if ($u->UserName() == $userid) { // lucky: current user (session)
360             $prefs = $u->getPreferences();
361             $request->_user->_level = WIKIAUTH_USER;
362             $request->_prefs->set('emailVerified', true);
363         } else {  // not current user
364             if (ENABLE_USER_NEW) {
365                 $u = WikiUser($userid);
366                 $u->getPreferences();
367                 $prefs = &$u->_prefs;
368             } else {
369                 $u = new WikiUser($request, $userid);
370                 $prefs = $u->getPreferences();
371             }
372             $u->_level = WIKIAUTH_USER;
373             $request->setUser($u);
374             $request->_prefs->set('emailVerified', true);
375         }
376         unset($data[$id]);
377         $wikidb->set('ConfirmEmail', $data);
378         return HTML(HTML::h1("Confirm E-mail address"),
379                     HTML::p("Your e-mail address has now been confirmed."));
380     }
381 }
382
383
384 // $Log: not supported by cvs2svn $
385 // Revision 1.10  2007/05/01 16:14:21  rurban
386 // fix cache
387 //
388 // Revision 1.9  2007/03/10 18:22:51  rurban
389 // Patch 1677950 by Erwann Penet
390 //
391 // Revision 1.8  2007/01/25 07:41:54  rurban
392 // Add wikimail.log default on unix
393 //
394 // Revision 1.7  2007/01/20 11:25:38  rurban
395 // Fix onDeletePage warning and content
396 //
397 // Revision 1.6  2007/01/09 12:34:55  rurban
398 // Fix typo (syntax error)
399 //
400 // Revision 1.5  2007/01/07 18:42:58  rurban
401 // Add MAILER_LOG logfile
402 //
403 // Revision 1.4  2007/01/04 16:47:49  rurban
404 // improve text
405 //
406 // Revision 1.3  2006/12/24 13:35:43  rurban
407 // added experimental EMailConfirm auth. (not yet tested)
408 // requires actionpage ConfirmEmail
409 // TBD: purge expired cookies
410 //
411 // Revision 1.2  2006/12/23 11:50:45  rurban
412 // added missing result init
413 //
414 // Revision 1.1  2006/12/22 17:59:55  rurban
415 // Move mailer functions into seperate MailNotify.php
416 //
417
418 // Local Variables:
419 // mode: php
420 // tab-width: 8
421 // c-basic-offset: 4
422 // c-hanging-comment-ender-p: nil
423 // indent-tabs-mode: nil
424 // End:   
425 ?>