]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/MailNotify.php
add SemanticAttributeSearchQuery description
[SourceForge/phpwiki.git] / lib / MailNotify.php
1 <?php //-*-php-*-
2 rcs_id('$Id: MailNotify.php,v 1.3 2006-12-24 13:35:43 rurban Exp $');
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 class MailNotify {
27
28     function MailNotify($pagename) {
29         $this->pagename = $pagename; /* which page */
30         $this->emails  = array();    /* to whch addresses */
31         $this->userids = array();    /* corresponding array of displayed names, 
32                                       dont display the email addersses */
33         /* from: from which the mail appears to be */
34         $this->from = $this->fromId();
35     }
36
37     function fromId() {
38         global $request;
39         return $request->_user->getId() . '@' .  $request->get('REMOTE_HOST');
40     }
41
42     function userEmail($userid, $doverify = true) {
43         global $request;
44         $u = $request->getUser();
45         if ($u->UserName() == $userid) { // lucky: current user
46             $prefs = $u->getPreferences();
47             $email = $prefs->get('email');
48             // do a dynamic emailVerified check update
49             if ($doverify and !$request->_prefs->get('emailVerified'))
50                 $email = '';
51         } else {  // not current user
52             if (ENABLE_USER_NEW) {
53                 $u = WikiUser($userid);
54                 $u->getPreferences();
55                 $prefs = &$u->_prefs;
56             } else {
57                 $u = new WikiUser($request, $userid);
58                 $prefs = $u->getPreferences();
59             }
60             $email = $prefs->get('email');
61             if ($doverify and !$prefs->get('emailVerified')) {
62                 $email = '';
63             }
64         }
65         return $email;
66     }
67
68     /**
69      * getPageChangeEmails($notify)
70      * @param  $notify: hash ( page => (userid => userhash) )
71      * @return array
72      *         unique array of ($emails, $userids)
73      */
74     function getPageChangeEmails($notify) {
75         global $request;
76         $emails = array(); $userids = array();
77         foreach ($notify as $page => $users) {
78             if (glob_match($page, $this->pagename)) {
79                 foreach ($users as $userid => $user) {
80                     if (!$user) { // handle the case for ModeratePage: 
81                                   // no prefs, just userid's.
82                         $emails[] = $this->userEmail($userid, false);
83                         $userids[] = $userid;
84                     } else {
85                         if (!empty($user['verified']) and !empty($user['email'])) {
86                             $emails[]  = $user['email'];
87                             $userids[] = $userid;
88                         } elseif (!empty($user['email'])) {
89                             // do a dynamic emailVerified check update
90                             $email = $this->userEmail($userid, true);
91                             if ($email) {
92                                 $notify[$page][$userid]['verified'] = 1;
93                                 $request->_dbi->set('notify', $notify);
94                                 $emails[] = $email;
95                                 $userids[] = $userid;
96                             }
97                         }
98                         // ignore verification
99                         /*
100                         if (DEBUG) {
101                             if (!in_array($user['email'],$emails))
102                                 $emails[] = $user['email'];
103                         }
104                         */
105                     }
106                 }
107             }
108         }
109         $this->emails = array_unique($emails);
110         $this->userids = array_unique($userids);
111         return array($this->emails, $this->userids);
112     }
113     
114     function sendMail($subject, $content, 
115                       $notice = _("PageChange Notification of %s"),
116                       $silent = false)
117     {
118         global $request;
119         $emails = $this->emails;
120         $from = $this->from;
121         if (mail(array_shift($emails),
122                  "[".WIKI_NAME."] ".$subject, 
123                  $subject."\n".$content,
124                  "From: $from\r\nBcc: ".join(',', $emails)
125                  ))
126         {
127             if (!$silent)
128                 trigger_error(sprintf($notice, $this->pagename)
129                               . " "
130                               . sprintf(_("sent to %s"), join(',',$this->userids)),
131                               E_USER_NOTICE);
132             return true;
133         } else {
134             trigger_error(sprintf($notice, $this->pagename)
135                           . " "
136                           . sprintf(_("Error: Couldn't send to %s"), join(',',$this->userids)), 
137                           E_USER_WARNING);
138             return false;
139         }
140     }
141     
142     /**
143      * Send udiff for a changed page to multiple users.
144      * See rename and remove methods also
145      */
146     function sendPageChangeNotification(&$wikitext, $version, &$meta) {
147
148         global $request;
149
150         if (@is_array($request->_deferredPageChangeNotification)) {
151             // collapse multiple changes (loaddir) into one email
152             $request->_deferredPageChangeNotification[] = 
153                 array($this->pagename, $this->emails, $this->userids);
154             return;
155         }
156         $backend = &$this->_wikidb->_backend;
157         //$backend = &$request->_dbi->_backend;
158         $subject = _("Page change").' '.urlencode($this->pagename);
159         $previous = $backend->get_previous_version($this->pagename, $version);
160         if (!isset($meta['mtime'])) $meta['mtime'] = time();
161         if ($previous) {
162             $difflink = WikiURL($this->pagename, array('action'=>'diff'), true);
163             $dbh = &$request->getDbh();
164             $cache = &$dbh->_wikidb->_cache;
165             //$cache = &$request->_dbi->_cache;
166             $content = explode("\n", $wikitext);
167             $prevdata = $cache->get_versiondata($this->pagename, $previous, true);
168             if (empty($prevdata['%content']))
169                 $prevdata = $backend->get_versiondata($this->pagename, $previous, true);
170             $other_content = explode("\n", $prevdata['%content']);
171             
172             include_once("lib/difflib.php");
173             $diff2 = new Diff($other_content, $this_content);
174             //$context_lines = max(4, count($other_content) + 1,
175             //                     count($this_content) + 1);
176             $fmt = new UnifiedDiffFormatter(/*$context_lines*/);
177             $content  = $this->pagename . " " . $previous . " " . 
178                 Iso8601DateTime($prevdata['mtime']) . "\n";
179             $content .= $this->pagename . " " . $version . " " .  
180                 Iso8601DateTime($meta['mtime']) . "\n";
181             $content .= $fmt->format($diff2);
182             
183         } else {
184             $difflink = WikiURL($this->pagename,array(),true);
185             $content = $this->pagename . " " . $version . " " .  
186                 Iso8601DateTime($meta['mtime']) . "\n";
187             $content .= _("New page");
188         }
189         $editedby = sprintf(_("Edited by: %s"), $this->from);
190         //$editedby = sprintf(_("Edited by: %s"), $meta['author']);
191         $this->sendMail($subject, 
192                         $editedby."\n".$difflink."\n\n".$content);
193     }
194
195     /** 
196      * support mass rename / remove (not yet tested)
197      */
198     function sendPageRenameNotification ($to, &$meta) {
199         global $request;
200
201         if (@is_array($request->_deferredPageRenameNotification)) {
202             $request->_deferredPageRenameNotification[] = 
203                 array($this->pagename, $to, $meta, $this->emails, $this->userids);
204         } else {
205             $pagename = $this->pagename;
206             //$editedby = sprintf(_("Edited by: %s"), $meta['author']) . ' ' . $meta['author_id'];
207             $editedby = sprintf(_("Edited by: %s"), $this->from);
208             $subject = sprintf(_("Page rename %s to %s"), urlencode($pagename), urlencode($to));
209             $link = WikiURL($to, true);
210             $this->sendMail($subject, 
211                             $editedby."\n".$link."\n\n"."Renamed $pagename to $to");
212         }
213     }
214
215     /**
216      * The handlers:
217      */
218     function onChangePage (&$wikidb, &$wikitext, $version, &$meta) {
219         $result = true;
220         if (!isa($GLOBALS['request'],'MockRequest')) {
221             $notify = $wikidb->_wikidb->get('notify');
222             /* Generate notification emails? */
223             if (!empty($notify) and is_array($notify)) {
224                 if (empty($this->pagename))
225                     $this->pagename = $meta['pagename'];
226                 //TODO: defer it (quite a massive load if you MassRevert some pages).
227                 //TODO: notification class which catches all changes,
228                 //  and decides at the end of the request what to mail. (type, page, who, what, users, emails)
229                 // could be used for PageModeration and RSS2 Cloud xml-rpc also.
230                 $this->getPageChangeEmails($notify);
231                 if (!empty($this->emails)) {
232                     $result = $this->sendPageChangeNotification($wikitext, $version, $meta);
233                 }
234             }
235         }
236         return $result;
237     }
238
239     function onDeletePage (&$wikidb, $pagename) {
240         $result = true;
241         /* Generate notification emails? */
242         if (! $wikidb->isWikiPage($pagename) and !isa($GLOBALS['request'],'MockRequest')) {
243             $notify = $wikidb->get('notify');
244             if (!empty($notify) and is_array($notify)) {
245                 //TODO: deferr it (quite a massive load if you remove some pages).
246                 //TODO: notification class which catches all changes,
247                 //  and decides at the end of the request what to mail. (type, page, who, what, users, emails)
248                 // could be used for PageModeration and RSS2 Cloud xml-rpc also.
249                 $page = new WikiDB_Page($wikidb, $pagename);
250                 $page->getPageChangeEmails($notify);
251                 if (!empty($this->emails)) {
252                     $editedby = sprintf(_("Removed by: %s"), $this->from); // Todo: host_id
253                     $emails = join(',', $emails);
254                     $subject = sprintf(_("Page removed %s"), urlencode($pagename));
255                     $result = $this->sendMail($subject, 
256                                               $editedby."\n"."Deleted $pagename"."\n\n".$content);
257                 }
258             }
259         }
260         //How to create a RecentChanges entry with explaining summary? Dynamically
261         /*
262           $page = $this->getPage($pagename);
263           $current = $page->getCurrentRevision();
264           $meta = $current->_data;
265           $version = $current->getVersion();
266           $meta['summary'] = _("removed");
267           $page->save($current->getPackedContent(), $version + 1, $meta);
268         */
269         return $result;
270     }
271
272     function onRenamePage (&$wikidb, $oldpage, $new_pagename) {
273         $result = true;
274         if (!isa($GLOBALS['request'], 'MockRequest')) {
275             $notify = $wikidb->get('notify');
276             if (!empty($notify) and is_array($notify)) {
277                 $this->getPageChangeEmails($notify);
278                 if (!empty($this->emails)) {
279                     $newpage = $wikidb->getPage($new_pagename);
280                     $current = $newpage->getCurrentRevision();
281                     $meta = $current->_data;
282                     $this->pagename = $oldpage;
283                     $result = $this->sendPageRenameNotification($new_pagename, $meta);
284                 }
285             }
286         }
287     }
288
289     /**
290      * send mail to user and store the cookie in the db
291      * wikiurl?action=ConfirmEmail&id=bla
292      */
293     function sendEmailConfirmation ($email, $userid) {
294         $id = rand_ascii_readable(16);
295         $wikidb = $GLOBALS['request']->getDbh();
296         $data = $wikidb->get('ConfirmEmail');
297         while(!empty($data[$id])) { // id collision
298             $id = rand_ascii_readable(16);
299         }
300         $subject = WIKI_NAME . " " . _("e-mail address confirmation");
301         $ip = $request->get('REMOTE_HOST');
302         $expire_date = time() + 7*86400;
303         $content = fmt("Someone, probably you from IP address %s, has registered an
304 account \"%s\" with this e-mail address on %s.
305
306 To confirm that this account really does belong to you and activate
307 e-mail features on %s, open this link in your browser:
308
309 %s
310
311 If this is *not* you, don't follow the link. This confirmation code
312 will expire at %s.", 
313                        $ip, $userid, WIKI_NAME, WIKI_NAME, 
314                        WikiURL(HOME_PAGE, array('action' => 'ConfirmEmail',
315                                                 'id' => $id), 
316                                true),
317                        CTime($expire_date));
318         $this->sendMail($subject, $content, "", true);
319         $data[$id] = array('email' => $email,
320                            'userid' => $userid,
321                            'expire' => $expire_date);
322         $wikidb->set('ConfirmEmail', $data);
323         return '';
324     }
325
326     function checkEmailConfirmation () {
327         global $request;
328         $wikidb = $request->getDbh();
329         $data = $wikidb->get('ConfirmEmail');
330         $id = $request->getArg('id');
331         if (empty($data[$id])) { // id not found
332             return HTML(HTML::h1("Confirm E-mail address"),
333                         HTML::h1("Sorry! Wrong URL"));
334         }
335         // upgrade the user
336         $userid = $data['userid'];
337         $email = $data['email'];
338         $u = $request->getUser();
339         if ($u->UserName() == $userid) { // lucky: current user (session)
340             $prefs = $u->getPreferences();
341             $request->_user->_level = WIKIAUTH_USER;
342             $request->_prefs->set('emailVerified', true);
343         } else {  // not current user
344             if (ENABLE_USER_NEW) {
345                 $u = WikiUser($userid);
346                 $u->getPreferences();
347                 $prefs = &$u->_prefs;
348             } else {
349                 $u = new WikiUser($request, $userid);
350                 $prefs = $u->getPreferences();
351             }
352             $u->_level = WIKIAUTH_USER;
353             $request->setUser($u);
354             $request->_prefs->set('emailVerified', true);
355         }
356         unset($data[$id]);
357         $wikidb->set('ConfirmEmail', $data);
358         return HTML(HTML::h1("Confirm E-mail address"),
359                     HTML::p("Your e-mail address has now been confirmed."));
360     }
361 }
362
363
364 // $Log: not supported by cvs2svn $
365 // Revision 1.2  2006/12/23 11:50:45  rurban
366 // added missing result init
367 //
368 // Revision 1.1  2006/12/22 17:59:55  rurban
369 // Move mailer functions into seperate MailNotify.php
370 //
371
372 // Local Variables:
373 // mode: php
374 // tab-width: 8
375 // c-basic-offset: 4
376 // c-hanging-comment-ender-p: nil
377 // indent-tabs-mode: nil
378 // End:   
379 ?>