]> git.mxchange.org Git - friendica.git/blob - include/enotify.php
Merge pull request #646 from annando/master
[friendica.git] / include / enotify.php
1 <?php
2
3 require_once('include/email.php');
4
5 function notification($params) {
6
7         logger('notification: entry', LOGGER_DEBUG);
8
9         $a = get_app();
10
11         // from here on everything is in the recipients language
12
13         push_lang($params['language']);
14
15
16         $banner = t('Friendica Notification');
17         $product = FRIENDICA_PLATFORM;
18         $siteurl = $a->get_baseurl(true);
19         $thanks = t('Thank You,');
20         $sitename = get_config('config','sitename');
21         $site_admin = sprintf( t('%s Administrator'), $sitename);
22
23         $sender_name = $product;
24         $hostname = $a->get_hostname();
25         if(strpos($hostname,':'))
26                 $hostname = substr($hostname,0,strpos($hostname,':'));
27
28         $sender_email = t('noreply') . '@' . $hostname;
29         $additional_mail_header = "";
30
31         if(array_key_exists('item',$params)) {
32                 $title = $params['item']['title'];
33                 $body = $params['item']['body'];
34         }
35         else {
36                 $title = $body = '';
37         }
38
39         // e.g. "your post", "David's photo", etc.
40         $possess_desc = t('%s <!item_type!>');
41
42         if($params['type'] == NOTIFY_MAIL) {
43
44                 $subject =      sprintf( t('[Friendica:Notify] New mail received at %s'),$sitename);
45
46                 $preamble = sprintf( t('%1$s sent you a new private message at %2$s.'),$params['source_name'],$sitename);
47                 $epreamble = sprintf( t('%1$s sent you %2$s.'),'[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]', '[url=$itemlink]' . t('a private message') . '[/url]');
48                 $sitelink = t('Please visit %s to view and/or reply to your private messages.');
49                 $tsitelink = sprintf( $sitelink, $siteurl . '/message/' . $params['item']['id'] );
50                 $hsitelink = sprintf( $sitelink, '<a href="' . $siteurl . '/message/' . $params['item']['id'] . '">' . $sitename . '</a>');
51                 $itemlink = $siteurl . '/message/' . $params['item']['id'];
52         }
53
54         if($params['type'] == NOTIFY_COMMENT) {
55 //              logger("notification: params = " . print_r($params, true), LOGGER_DEBUG);
56
57                 $parent_id = $params['parent'];
58
59                 // Check to see if there was already a tag notify or comment notify for this post.
60                 // If so don't create a second notification
61                 
62                 $p = null;
63                 $p = q("select id from notify where ( type = %d or type = %d ) and link = '%s' and uid = %d limit 1",
64                         intval(NOTIFY_TAGSELF),
65                         intval(NOTIFY_COMMENT),
66                         dbesc($params['link']),
67                         intval($params['uid'])
68                 );
69                 if($p and count($p)) {
70                         pop_lang();
71                         return;
72                 }
73         
74
75                 // if it's a post figure out who's post it is.
76
77                 $p = null;
78
79                 if($params['otype'] === 'item' && $parent_id) {
80                         $p = q("select * from item where id = %d and uid = %d limit 1",
81                                 intval($parent_id),
82                                 intval($params['uid'])
83                         );
84                 }
85
86                 $item_post_type = item_post_type($p[0]);
87                 //$possess_desc = str_replace('<!item_type!>',$possess_desc);
88
89                 // "a post"
90                 $dest_str = sprintf(t('%1$s commented on [url=%2$s]a %3$s[/url]'),
91                                                                 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
92                                                                 $itemlink,
93                                                                 $item_post_type);
94
95                 // "George Bull's post"
96                 if($p)
97                         $dest_str = sprintf(t('%1$s commented on [url=%2$s]%3$s\'s %4$s[/url]'),
98                                                 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
99                                                 $itemlink,
100                                                 $p[0]['author-name'],
101                                                 $item_post_type);
102                 
103                 // "your post"
104                 if($p[0]['owner-name'] == $p[0]['author-name'] && $p[0]['wall'])
105                         $dest_str = sprintf(t('%1$s commented on [url=%2$s]your %3$s[/url]'),
106                                                                 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
107                                                                 $itemlink,
108                                                                 $item_post_type);
109
110                 // Some mail softwares relies on subject field for threading.
111                 // So, we cannot have different subjects for notifications of the same thread.
112                 // Before this we have the name of the replier on the subject rendering 
113                 // differents subjects for messages on the same thread.
114
115                 $subject = sprintf( t('[Friendica:Notify] Comment to conversation #%1$d by %2$s'), $parent_id, $params['source_name']);
116                 $preamble = sprintf( t('%s commented on an item/conversation you have been following.'), $params['source_name']); 
117                 $epreamble = $dest_str; 
118
119                 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
120                 $tsitelink = sprintf( $sitelink, $siteurl );
121                 $hsitelink = sprintf( $sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
122                 $itemlink =  $params['link'];
123         }
124
125         if($params['type'] == NOTIFY_WALL) {
126                 $subject = sprintf( t('[Friendica:Notify] %s posted to your profile wall') , $params['source_name']);
127
128                 $preamble = sprintf( t('%1$s posted to your profile wall at %2$s') , $params['source_name'], $sitename);
129                 
130                 $epreamble = sprintf( t('%1$s posted to [url=%2$s]your wall[/url]') , 
131                                                                 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
132                                                                 $params['link']); 
133                 
134                 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
135                 $tsitelink = sprintf( $sitelink, $siteurl );
136                 $hsitelink = sprintf( $sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
137                 $itemlink =  $params['link'];
138         }
139
140         if($params['type'] == NOTIFY_TAGSELF) {
141                 $subject =      sprintf( t('[Friendica:Notify] %s tagged you') , $params['source_name']);
142                 $preamble = sprintf( t('%1$s tagged you at %2$s') , $params['source_name'], $sitename);
143                 $epreamble = sprintf( t('%1$s [url=%2$s]tagged you[/url].') , 
144                                                                 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
145                                                                 $params['link']); 
146
147                 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
148                 $tsitelink = sprintf( $sitelink, $siteurl );
149                 $hsitelink = sprintf( $sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
150                 $itemlink =  $params['link'];
151         }
152
153         if($params['type'] == NOTIFY_POKE) {
154
155                 $subject =      sprintf( t('[Friendica:Notify] %1$s poked you') , $params['source_name']);
156                 $preamble = sprintf( t('%1$s poked you at %2$s') , $params['source_name'], $sitename);
157                 $epreamble = sprintf( t('%1$s [url=%2$s]poked you[/url].') , 
158                                                                 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
159                                                                 $params['link']); 
160
161                 $subject = str_replace('poked', t($params['activity']), $subject);
162                 $preamble = str_replace('poked', t($params['activity']), $preamble);
163                 $epreamble = str_replace('poked', t($params['activity']), $epreamble);
164
165                 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
166                 $tsitelink = sprintf( $sitelink, $siteurl );
167                 $hsitelink = sprintf( $sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
168                 $itemlink =  $params['link'];
169         }
170
171         if($params['type'] == NOTIFY_TAGSHARE) {
172                 $subject =      sprintf( t('[Friendica:Notify] %s tagged your post') , $params['source_name']);
173                 $preamble = sprintf( t('%1$s tagged your post at %2$s') , $params['source_name'], $sitename);
174                 $epreamble = sprintf( t('%1$s tagged [url=%2$s]your post[/url]') ,
175                                                                 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]',
176                                                                 $itemlink); 
177
178                 $sitelink = t('Please visit %s to view and/or reply to the conversation.');
179                 $tsitelink = sprintf( $sitelink, $siteurl );
180                 $hsitelink = sprintf( $sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
181                 $itemlink =  $params['link'];
182         }
183
184         if($params['type'] == NOTIFY_INTRO) {
185                 $subject = sprintf( t('[Friendica:Notify] Introduction received'));
186                 $preamble = sprintf( t('You\'ve received an introduction from \'%1$s\' at %2$s'), $params['source_name'], $sitename); 
187                 $epreamble = sprintf( t('You\'ve received [url=%1$s]an introduction[/url] from %2$s.'),
188                                                                 $itemlink,
189                                                                 '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]'); 
190                 $body = sprintf( t('You may visit their profile at %s'),$params['source_link']);
191
192                 $sitelink = t('Please visit %s to approve or reject the introduction.');
193                 $tsitelink = sprintf( $sitelink, $siteurl );
194                 $hsitelink = sprintf( $sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
195                 $itemlink =  $params['link'];
196         }
197
198         if($params['type'] == NOTIFY_SUGGEST) {
199                 $subject = sprintf( t('[Friendica:Notify] Friend suggestion received'));
200                 $preamble = sprintf( t('You\'ve received a friend suggestion from \'%1$s\' at %2$s'), $params['source_name'], $sitename); 
201                 $epreamble = sprintf( t('You\'ve received [url=%1$s]a friend suggestion[/url] for %2$s from %3$s.'),
202                                                                         $itemlink,
203                                                                         '[url=' . $params['item']['url'] . ']' . $params['item']['name'] . '[/url]',
204                                                                         '[url=' . $params['source_link'] . ']' . $params['source_name'] . '[/url]'); 
205                                                                         
206                 $body = t('Name:') . ' ' . $params['item']['name'] . "\n";
207                 $body .= t('Photo:') . ' ' . $params['item']['photo'] . "\n";
208                 $body .= sprintf( t('You may visit their profile at %s'),$params['item']['url']);
209
210                 $sitelink = t('Please visit %s to approve or reject the suggestion.');
211                 $tsitelink = sprintf( $sitelink, $siteurl );
212                 $hsitelink = sprintf( $sitelink, '<a href="' . $siteurl . '">' . $sitename . '</a>');
213                 $itemlink =  $params['link'];
214         }
215
216         if($params['type'] == NOTIFY_CONFIRM) {
217         }
218
219         if($params['type'] == NOTIFY_SYSTEM) {
220
221         }
222
223         $h = array(
224                 'params'    => $params, 
225                 'subject'   => $subject,
226                 'preamble'  => $preamble, 
227                 'epreamble' => $epreamble, 
228                 'body'      => $body, 
229                 'sitelink'  => $sitelink,
230                 'tsitelink' => $tsitelink,
231                 'hsitelink' => $hsitelink,
232                 'itemlink'  => $itemlink
233         );
234                 
235         call_hooks('enotify',$h);
236
237         $subject   = $h['subject'];
238         $preamble  = $h['preamble'];
239         $epreamble = $h['epreamble'];
240         $body      = $h['body'];
241         $sitelink  = $h['sitelink'];
242         $tsitelink = $h['tsitelink'];
243         $hsitelink = $h['hsitelink'];
244         $itemlink  = $h['itemlink']; 
245
246
247         require_once('include/html2bbcode.php');        
248
249         do {
250                 $dups = false;
251                 $hash = random_string();
252         $r = q("SELECT `id` FROM `notify` WHERE `hash` = '%s' LIMIT 1",
253                         dbesc($hash));
254                 if(count($r))
255                         $dups = true;
256         } while($dups == true);
257
258
259         $datarray = array();
260         $datarray['hash']  = $hash;
261         $datarray['name']  = $params['source_name'];
262         $datarray['url']   = $params['source_link'];
263         $datarray['photo'] = $params['source_photo'];
264         $datarray['date']  = datetime_convert();
265         $datarray['uid']   = $params['uid'];
266         $datarray['link']  = $itemlink;
267         $datarray['parent'] = $parent_id;
268         $datarray['type']  = $params['type'];
269         $datarray['verb']  = $params['verb'];
270         $datarray['otype'] = $params['otype'];
271  
272         call_hooks('enotify_store', $datarray);
273
274         // create notification entry in DB
275
276         $r = q("insert into notify (hash,name,url,photo,date,uid,link,parent,type,verb,otype)
277                 values('%s','%s','%s','%s','%s',%d,'%s',%d,%d,'%s','%s')",
278                 dbesc($datarray['hash']),
279                 dbesc($datarray['name']),
280                 dbesc($datarray['url']),
281                 dbesc($datarray['photo']),
282                 dbesc($datarray['date']),
283                 intval($datarray['uid']),
284                 dbesc($datarray['link']),
285                 intval($datarray['parent']),
286                 intval($datarray['type']),
287                 dbesc($datarray['verb']),
288                 dbesc($datarray['otype'])
289         );
290
291         $r = q("select id from notify where hash = '%s' and uid = %d limit 1",
292                 dbesc($hash),
293                 intval($params['uid'])
294         );
295         if($r)
296                 $notify_id = $r[0]['id'];
297         else {
298                 pop_lang();
299                 return;
300         }
301
302         // we seem to have a lot of duplicate comment notifications due to race conditions, mostly from forums
303         // After we've stored everything, look again to see if there are any duplicates and if so remove them
304
305         $p = null;
306         $p = q("select id from notify where ( type = %d or type = %d ) and link = '%s' and uid = %d order by id",
307                 intval(NOTIFY_TAGSELF),
308                 intval(NOTIFY_COMMENT),
309                 dbesc($params['link']),
310                 intval($params['uid'])
311         );
312         if($p && (count($p) > 1)) {
313                 for ($d = 1; $d < count($p); $d ++) {
314                         q("delete from notify where id = %d limit 1",
315                                 intval($p[$d]['id'])
316                         );
317                 }
318
319                 // only continue on if we stored the first one
320
321                 if($notify_id != $p[0]['id']) {
322                         pop_lang();
323                         return;
324                 }
325         }
326
327
328
329
330
331
332
333
334         $itemlink = $a->get_baseurl() . '/notify/view/' . $notify_id;
335         $msg = replace_macros($epreamble,array('$itemlink' => $itemlink));
336         $r = q("update notify set msg = '%s' where id = %d and uid = %d limit 1",
337                 dbesc($msg),
338                 intval($notify_id),
339                 intval($params['uid'])
340         );
341                 
342
343         // send email notification if notification preferences permit
344
345         require_once('include/bbcode.php');
346         if((intval($params['notify_flags']) & intval($params['type'])) || $params['type'] == NOTIFY_SYSTEM) {
347
348                 logger('notification: sending notification email');
349
350                 $id_for_parent = "${params['parent']}@${hostname}";
351
352                 // Is this the first email notification for this parent item and user?
353                 
354                 $r = q("select `id` from `notify-threads` where `master-parent-item` = %d and `receiver-uid` = %d limit 1", 
355                         intval($params['parent']),
356                         intval($params['uid']) );
357
358                 // If so, create the record of it and use a message-id smtp header.
359
360                 if(!$r) {
361                         logger("notify_id:" . intval($notify_id). ", parent: " . intval($params['parent']) . "uid: " . 
362 intval($params['uid']), LOGGER_DEBUG);
363                         $r = q("insert into `notify-threads` (`notify-id`, `master-parent-item`, `receiver-uid`, `parent-item`)
364                                 values(%d,%d,%d,%d)",
365                                 intval($notify_id),
366                                 intval($params['parent']),
367                                 intval($params['uid']), 
368                                 0 );
369
370                         $additional_mail_header .= "Message-ID: <${id_for_parent}>\n";
371                         $log_msg = "include/enotify: No previous notification found for this parent:\n" . 
372                                         "  parent: ${params['parent']}\n" . "  uid   : ${params['uid']}\n";
373                         logger($log_msg, LOGGER_DEBUG);
374                 }
375
376                 // If not, just "follow" the thread.
377
378                 else {
379                         $additional_mail_header = "References: <${id_for_parent}>\nIn-Reply-To: <${id_for_parent}>\n";
380                         logger("include/enotify: There's already a notification for this parent:\n" . print_r($r, true), LOGGER_DEBUG);
381                 }
382
383
384
385                 $textversion = strip_tags(html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r", "\\n"), "\n",
386                         $body))),ENT_QUOTES,'UTF-8'));
387                 $htmlversion = html_entity_decode(bbcode(stripslashes(str_replace(array("\\r\\n", "\\r","\\n\\n" ,"\\n"), 
388                         "<br />\n",$body))));
389
390                 $datarray = array();
391                 $datarray['banner'] = $banner;
392                 $datarray['product'] = $product;
393                 $datarray['preamble'] = $preamble;
394                 $datarray['sitename'] = $sitename;
395                 $datarray['siteurl'] = $siteurl;
396                 $datarray['type'] = $params['type'];
397                 $datarray['parent'] = $params['parent'];
398                 $datarray['source_name'] = $params['source_name'];
399                 $datarray['source_link'] = $params['source_link'];
400                 $datarray['source_photo'] = $params['source_photo'];
401                 $datarray['uid'] = $params['uid'];
402                 $datarray['username'] = $params['to_name'];
403                 $datarray['hsitelink'] = $hsitelink;
404                 $datarray['tsitelink'] = $tsitelink;
405                 $datarray['hitemlink'] = '<a href="' . $itemlink . '">' . $itemlink . '</a>';
406                 $datarray['titemlink'] = $itemlink;
407                 $datarray['thanks'] = $thanks;
408                 $datarray['site_admin'] = $site_admin;
409                 $datarray['title'] = stripslashes($title);
410                 $datarray['htmlversion'] = $htmlversion;
411                 $datarray['textversion'] = $textversion;
412                 $datarray['subject'] = $subject;
413                 $datarray['headers'] = $additional_mail_header;
414
415                 call_hooks('enotify_mail', $datarray);
416
417                 // check whether sending post content in email notifications is allowed
418                 $content_allowed = !get_config('system','enotify_no_content');
419
420                 // load the template for private message notifications
421                 $tpl = get_markup_template('email_notify_html.tpl');
422                 $email_html_body = replace_macros($tpl,array(
423                         '$banner'       => $datarray['banner'],
424                         '$product'      => $datarray['product'],
425                         '$preamble'     => $datarray['preamble'],
426                         '$sitename'     => $datarray['sitename'],
427                         '$siteurl'      => $datarray['siteurl'],
428                         '$source_name'  => $datarray['source_name'],
429                         '$source_link'  => $datarray['source_link'],
430                         '$source_photo' => $datarray['source_photo'],
431                         '$username'     => $datarray['to_name'],
432                         '$hsitelink'    => $datarray['hsitelink'],
433                         '$hitemlink'    => $datarray['hitemlink'],
434                         '$thanks'       => $datarray['thanks'],
435                         '$site_admin'   => $datarray['site_admin'],
436                         '$title'                => $datarray['title'],
437                         '$htmlversion'  => $datarray['htmlversion'],
438                         '$content_allowed'      => $content_allowed,
439                 ));
440                 
441                 // load the template for private message notifications
442                 $tpl = get_markup_template('email_notify_text.tpl');
443                 $email_text_body = replace_macros($tpl,array(
444                         '$banner'       => $datarray['banner'],
445                         '$product'      => $datarray['product'],
446                         '$preamble'     => $datarray['preamble'],
447                         '$sitename'     => $datarray['sitename'],
448                         '$siteurl'      => $datarray['siteurl'],
449                         '$source_name'  => $datarray['source_name'],
450                         '$source_link'  => $datarray['source_link'],
451                         '$source_photo' => $datarray['source_photo'],
452                         '$username'     => $datarray['to_name'],
453                         '$tsitelink'    => $datarray['tsitelink'],
454                         '$titemlink'    => $datarray['titemlink'],
455                         '$thanks'       => $datarray['thanks'],
456                         '$site_admin'   => $datarray['site_admin'],
457                         '$title'                => $datarray['title'],
458                         '$textversion'  => $datarray['textversion'],    
459                         '$content_allowed'      => $content_allowed,
460                 ));
461
462 //              logger('text: ' . $email_text_body);
463
464                 // use the EmailNotification library to send the message
465
466                 enotify::send(array(
467                         'fromName' => $sender_name,
468                         'fromEmail' => $sender_email,
469                         'replyTo' => $sender_email,
470                         'toEmail' => $params['to_email'],
471                         'messageSubject' => $datarray['subject'],
472                         'htmlVersion' => $email_html_body,
473                         'textVersion' => $email_text_body,
474                         'additionalMailHeader' => $datarray['headers'],
475                 ));
476         }
477
478         pop_lang();
479
480 }
481
482 require_once('include/email.php');
483
484 class enotify {
485         /**
486          * Send a multipart/alternative message with Text and HTML versions
487          *
488          * @param fromName                      name of the sender
489          * @param fromEmail                     email fo the sender
490          * @param replyTo                       replyTo address to direct responses
491          * @param toEmail                       destination email address
492          * @param messageSubject        subject of the message
493          * @param htmlVersion           html version of the message
494          * @param textVersion           text only version of the message
495          * @param additionalMailHeader  additions to the smtp mail header
496          */
497         static public function send($params) {
498
499                 $fromName = email_header_encode(html_entity_decode($params['fromName'],ENT_QUOTES,'UTF-8'),'UTF-8'); 
500                 $messageSubject = email_header_encode(html_entity_decode($params['messageSubject'],ENT_QUOTES,'UTF-8'),'UTF-8');
501                 
502                 // generate a mime boundary
503                 $mimeBoundary   =rand(0,9)."-"
504                                 .rand(10000000000,9999999999)."-"
505                                 .rand(10000000000,9999999999)."=:"
506                                 .rand(10000,99999);
507
508                 // generate a multipart/alternative message header
509                 $messageHeader =
510                         $params['additionalMailHeader'] .
511                         "From: $fromName <{$params['fromEmail']}>\n" . 
512                         "Reply-To: $fromName <{$params['replyTo']}>\n" .
513                         "MIME-Version: 1.0\n" .
514                         "Content-Type: multipart/alternative; boundary=\"{$mimeBoundary}\"";
515
516                 // assemble the final multipart message body with the text and html types included
517                 $textBody       =       chunk_split(base64_encode($params['textVersion']));
518                 $htmlBody       =       chunk_split(base64_encode($params['htmlVersion']));
519                 $multipartMessageBody =
520                         "--" . $mimeBoundary . "\n" .                                   // plain text section
521                         "Content-Type: text/plain; charset=UTF-8\n" .
522                         "Content-Transfer-Encoding: base64\n\n" .
523                         $textBody . "\n" .
524                         "--" . $mimeBoundary . "\n" .                                   // text/html section
525                         "Content-Type: text/html; charset=UTF-8\n" .
526                         "Content-Transfer-Encoding: base64\n\n" .
527                         $htmlBody . "\n" .
528                         "--" . $mimeBoundary . "--\n";                                  // message ending
529
530                 // send the message
531                 $res = mail(
532                         $params['toEmail'],                                                                             // send to address
533                         $messageSubject,                                                                // subject
534                         $multipartMessageBody,                                                  // message body
535                         $messageHeader                                                                  // message headers
536                 );
537                 logger("notification: enotify::send header " . 'To: ' . $params['toEmail'] . "\n" . $messageHeader, LOGGER_DEBUG);
538                 logger("notification: enotify::send returns " . $res, LOGGER_DEBUG);
539         }
540 }
541 ?>