]> git.mxchange.org Git - friendica.git/blob - include/notifier.php
cb4dfe025fccd819118903b0efc69f39c622bb92
[friendica.git] / include / notifier.php
1 <?php
2 require_once("boot.php");
3
4 function notifier_run($argv, $argc){
5         global $a, $db;
6
7         if(is_null($a)){
8                 $a = new App;
9         }
10   
11         if(is_null($db)) {
12                 @include(".htconfig.php");
13                 require_once("dba.php");
14                 $db = new dba($db_host, $db_user, $db_pass, $db_data);
15                         unset($db_host, $db_user, $db_pass, $db_data);
16         }
17
18         require_once("session.php");
19         require_once("datetime.php");
20         require_once('include/items.php');
21         require_once('include/bbcode.php');
22
23         load_hooks();
24
25         if($argc < 3)
26                 return;
27
28         $a->set_baseurl(get_config('system','url'));
29
30         logger('notifier: invoked: ' . print_r($argv,true));
31
32         $cmd = $argv[1];
33
34         switch($cmd) {
35
36                 case 'mail':
37                 default:
38                         $item_id = intval($argv[2]);
39                         if(! $item_id){
40                                 return;
41                         }
42                         break;
43         }
44
45         $expire = false;
46         $top_level = false;
47         $recipients = array();
48         $url_recipients = array();
49
50         if($cmd === 'mail') {
51
52                 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
53                                 intval($item_id)
54                 );
55                 if(! count($message)){
56                         return;
57                 }
58                 $uid = $message[0]['uid'];
59                 $recipients[] = $message[0]['contact-id'];
60                 $item = $message[0];
61
62         }
63         elseif($cmd === 'expire') {
64                 $expire = true;
65                 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1 
66                         AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP - INTERVAL 10 MINUTE",
67                         intval($item_id)
68                 );
69                 $uid = $item_id;
70                 $item_id = 0;
71                 if(! count($items))
72                         return;
73         }
74         else {
75
76                 // find ancestors
77                 $r = q("SELECT * FROM `item` WHERE `id` = %d LIMIT 1",
78                         intval($item_id)
79                 );
80
81                 if((! count($r)) || (! intval($r[0]['parent']))) {
82                         return;
83                 }
84
85                 $parent_item = $r[0];
86                 $parent_id = intval($r[0]['parent']);
87                 $uid = $r[0]['uid'];
88                 $updated = $r[0]['edited'];
89
90                 $items = q("SELECT * FROM `item` WHERE `parent` = %d ORDER BY `id` ASC",
91                         intval($parent_id)
92                 );
93
94                 if(! count($items)) {
95                         return;
96                 }
97
98                 // avoid race condition with deleting entries
99
100                 if($items[0]['deleted']) {
101                         foreach($items as $item)
102                                 $item['deleted'] = 1;
103                 }
104
105                 if(count($items) == 1 && $items[0]['uri'] === $items[0]['parent-uri'])
106                         $top_level = true;
107         }
108
109         $r = q("SELECT `contact`.*, `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`, `user`.`page-flags` 
110                 FROM `contact` LEFT JOIN `user` ON `user`.`uid` = `contact`.`uid` 
111                 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
112                 intval($uid)
113         );
114
115         if(! count($r))
116                 return;
117
118         $owner = $r[0];
119
120         $hub = get_config('system','huburl');
121
122         // If this is a public conversation, notify the feed hub
123         $notify_hub = true;
124
125         // fill this in with a single salmon slap if applicable
126         $slap = '';
127
128         if($cmd != 'mail') {
129
130                 require_once('include/group.php');
131
132                 $parent = $items[0];
133
134                 if($parent['type'] === 'remote' && (! $expire)) {
135                         // local followup to remote post
136                         $followup = true;
137                         $notify_hub = false; // not public
138                         $conversant_str = dbesc($parent['contact-id']);
139                 }
140                 else {
141                         $followup = false;
142
143                         if((strlen($parent['allow_cid'])) 
144                                 || (strlen($parent['allow_gid'])) 
145                                 || (strlen($parent['deny_cid'])) 
146                                 || (strlen($parent['deny_gid']))) {
147                                 $notify_hub = false; // private recipients, not public
148                         }
149
150                         $allow_people = expand_acl($parent['allow_cid']);
151                         $allow_groups = expand_groups(expand_acl($parent['allow_gid']));
152                         $deny_people  = expand_acl($parent['deny_cid']);
153                         $deny_groups  = expand_groups(expand_acl($parent['deny_gid']));
154
155                         $conversants = array();
156
157                         foreach($items as $item) {
158                                 $recipients[] = $item['contact-id'];
159                                 $conversants[] = $item['contact-id'];
160                                 // pull out additional tagged people to notify (if public message)
161                                 if($notify_hub && strlen($item['inform'])) {
162                                         $people = explode(',',$item['inform']);
163                                         foreach($people as $person) {
164                                                 if(substr($person,0,4) === 'cid:') {
165                                                         $recipients[] = intval(substr($person,4));
166                                                         $conversants[] = intval(substr($person,4));
167                                                 }
168                                                 else {
169                                                         $url_recipients[] = substr($person,4);
170                                                 }
171                                         }
172                                 }
173                         }
174
175                         logger('notifier: url_recipients' . print_r($url_recipients,true));
176
177                         $conversants = array_unique($conversants);
178
179
180                         $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
181                         $deny = array_unique(array_merge($deny_people,$deny_groups));
182                         $recipients = array_diff($recipients,$deny);
183
184                         $conversant_str = dbesc(implode(', ',$conversants));
185                 }
186
187                 $r = q("SELECT * FROM `contact` WHERE `id` IN ( $conversant_str ) AND `blocked` = 0 AND `pending` = 0");
188
189
190                 if(count($r))
191                         $contacts = $r;
192         }
193
194         $feed_template = get_markup_template('atom_feed.tpl');
195         $mail_template = get_markup_template('atom_mail.tpl');
196
197         $atom = '';
198         $slaps = array();
199
200         $hubxml = feed_hublinks();
201
202         $birthday = feed_birthday($owner['uid'],$owner['timezone']);
203
204         if(strlen($birthday))
205                 $birthday = '<dfrn:birthday>' . xmlify($birthday) . '</dfrn:birthday>';
206
207         $atom .= replace_macros($feed_template, array(
208                         '$version'      => xmlify(FRIENDIKA_VERSION),
209                         '$feed_id'      => xmlify($a->get_baseurl() . '/profile/' . $owner['nickname'] ),
210                         '$feed_title'   => xmlify($owner['name']),
211                         '$feed_updated' => xmlify(datetime_convert('UTC', 'UTC', $updated . '+00:00' , ATOM_TIME)) ,
212                         '$hub'          => $hubxml,
213                         '$salmon'       => '',  // private feed, we don't use salmon here
214                         '$name'         => xmlify($owner['name']),
215                         '$profile_page' => xmlify($owner['url']),
216                         '$photo'        => xmlify($owner['photo']),
217                         '$thumb'        => xmlify($owner['thumb']),
218                         '$picdate'      => xmlify(datetime_convert('UTC','UTC',$owner['avatar-date'] . '+00:00' , ATOM_TIME)) ,
219                         '$uridate'      => xmlify(datetime_convert('UTC','UTC',$owner['uri-date']    . '+00:00' , ATOM_TIME)) ,
220                         '$namdate'      => xmlify(datetime_convert('UTC','UTC',$owner['name-date']   . '+00:00' , ATOM_TIME)) ,
221                         '$birthday'     => $birthday
222         ));
223
224         if($cmd === 'mail') {
225                 $notify_hub = false;  // mail is  not public
226
227                 $atom .= replace_macros($mail_template, array(
228                         '$name'         => xmlify($owner['name']),
229                         '$profile_page' => xmlify($owner['url']),
230                         '$thumb'        => xmlify($owner['thumb']),
231                         '$item_id'      => xmlify($item['uri']),
232                         '$subject'      => xmlify($item['title']),
233                         '$created'      => xmlify(datetime_convert('UTC', 'UTC', $item['created'] . '+00:00' , ATOM_TIME)),
234                         '$content'      => xmlify($item['body']),
235                         '$parent_id'    => xmlify($item['parent-uri'])
236                 ));
237         }
238         else {
239                 if($followup) {
240                         foreach($items as $item) {  // there is only one item
241                                 if(! $item['parent'])
242                                         continue;
243                                 if($item['id'] == $item_id) {
244                                         logger('notifier: followup: item: ' . print_r($item,true), LOGGER_DATA);
245                                         $slap  = atom_entry($item,'html',$owner,$owner,false);
246                                         $atom .= atom_entry($item,'text',$owner,$owner,false);
247                                 }
248                         }
249                 }
250                 else {
251                         foreach($items as $item) {
252
253                                 if(! $item['parent'])
254                                         continue;
255
256                                 $contact = get_item_contact($item,$contacts);
257                                 if(! $contact)
258                                         continue;
259
260                                 $atom .= atom_entry($item,'text',$contact,$owner,true);
261
262                                 if(($top_level) && ($notify_hub) && ($item['author-link'] === $item['owner-link']) && (! $expire)) 
263                                         $slaps[] = atom_entry($item,'html',$contact,$owner,true);
264                         }
265                 }
266         }
267         $atom .= '</feed>' . "\r\n";
268
269         logger('notifier: ' . $atom, LOGGER_DATA);
270
271         logger('notifier: slaps: ' . print_r($slaps,true), LOGGER_DATA);
272
273         // If this is a public message and pubmail is set on the parent, include all your email contacts
274
275         $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
276
277         if(! $mail_disabled) {
278                 if((! strlen($parent_item['allow_cid'])) && (! strlen($parent_item['allow_gid'])) 
279                         && (! strlen($parent_item['deny_cid'])) && (! strlen($parent_item['deny_gid'])) 
280                         && (intval($parent_item['pubmail']))) {
281                         $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
282                                 intval($uid),
283                                 dbesc(NETWORK_MAIL)
284                         );
285                         if(count($r)) {
286                                 foreach($r as $rr)
287                                         $recipients[] = $rr['id'];
288                         }
289                 }
290         }
291
292         if($followup)
293                 $recip_str = $parent['contact-id'];
294         else
295                 $recip_str = implode(', ', $recipients);
296
297         $r = q("SELECT * FROM `contact` WHERE `id` IN ( %s ) AND `blocked` = 0 AND `pending` = 0 ",
298                 dbesc($recip_str)
299         );
300
301         // delivery loop
302
303         require_once('include/salmon.php');
304
305         if(count($r)) {
306                 foreach($r as $contact) {
307                         if($contact['self'])
308                                 continue;
309
310                         $deliver_status = 0;
311
312                         switch($contact['network']) {
313                                 case 'dfrn':
314                                         logger('notifier: dfrndelivery: ' . $contact['name']);
315                                         $deliver_status = dfrn_deliver($owner,$contact,$atom);
316
317                                         logger('notifier: dfrn_delivery returns ' . $deliver_status);
318         
319                                         if($deliver_status == (-1)) {
320                                                 logger('notifier: delivery failed: queuing message');
321                                                 // queue message for redelivery
322                                                 q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`)
323                                                         VALUES ( %d, '%s', '%s', '%s') ",
324                                                         intval($contact['id']),
325                                                         dbesc(datetime_convert()),
326                                                         dbesc(datetime_convert()),
327                                                         dbesc($atom)
328                                                 );
329                                         }
330                                         break;
331                                 case 'stat':
332
333                                         if($followup && $contact['notify']) {
334                                                 logger('notifier: slapdelivery: ' . $contact['name']);
335                                                 $deliver_status = slapper($owner,$contact['notify'],$slap);
336
337                                                 if($deliver_status == (-1)) {
338                                                         // queue message for redelivery
339                                                         q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`)
340                                                                 VALUES ( %d, '%s', '%s', '%s') ",
341                                                                 intval($contact['id']),
342                                                                 dbesc(datetime_convert()),
343                                                                 dbesc(datetime_convert()),
344                                                                 dbesc($slap)
345                                                         );
346
347                                                 }
348         
349
350                                         }
351                                         else {
352
353                                                 // only send salmon if public - e.g. if it's ok to notify
354                                                 // a public hub, it's ok to send a salmon
355
356                                                 if((count($slaps)) && ($notify_hub) && (! $expire)) {
357                                                         logger('notifier: slapdelivery: ' . $contact['name']);
358                                                         foreach($slaps as $slappy) {
359                                                                 if($contact['notify']) {
360                                                                         $deliver_status = slapper($owner,$contact['notify'],$slappy);
361                                                                         if($deliver_status == (-1)) {
362                                                                                 // queue message for redelivery
363                                                                                 q("INSERT INTO `queue` ( `cid`, `created`, `last`, `content`)
364                                                                                         VALUES ( %d, '%s', '%s', '%s') ",
365                                                                                         intval($contact['id']),
366                                                                                         dbesc(datetime_convert()),
367                                                                                         dbesc(datetime_convert()),
368                                                                                         dbesc($slappy)
369                                                                                 );                                                              
370                                                                         }
371                                                                 }
372                                                         }
373                                                 }
374                                         }
375                                         break;
376                                 case 'mail':
377                                                 
378                                         // WARNING: does not currently convert to RFC2047 header encodings, etc.
379
380                                         $addr = $contact['addr'];
381                                         if(! strlen($addr))
382                                                 break;
383
384                                         if($cmd === 'wall-new' || $cmd === 'comment-new') {
385
386                                                 $it = null;
387                                                 if($cmd === 'wall-new') 
388                                                         $it = $items[0];
389                                                 else {
390                                                         $r = q("SELECT * FROM `item` WHERE `id` = %d AND `uid` = %d LIMIT 1", 
391                                                                 intval($argv[2]),
392                                                                 intval($uid)
393                                                         );
394                                                         if(count($r))
395                                                                 $it = $r[0];
396                                                 }
397                                                 if(! $it)
398                                                         break;
399                                                 
400
401
402                                                 $local_user = q("SELECT * FROM `user` WHERE `uid` = %d LIMIT 1",
403                                                         intval($uid)
404                                                 );
405                                                 if(! count($local_user))
406                                                         break;
407                                                 
408                                                 $reply_to = '';
409                                                 $r1 = q("SELECT * FROM `mailacct` WHERE `uid` = %d LIMIT 1",
410                                                         intval($uid)
411                                                 );
412                                                 if($r1 && $r1[0]['reply_to'])
413                                                         $reply_to = $r1[0]['reply_to'];
414         
415                                                 $subject  = (($it['title']) ? $it['title'] : t("\x28no subject\x29")) ;
416                                                 $headers  = 'From: ' . $local_user[0]['username'] . ' <' . $local_user[0]['email'] . '>' . "\n";
417
418                                                 if($reply_to)
419                                                         $headers .= 'Reply-to: ' . $reply_to . "\n";
420
421                                                 $headers .= 'Message-id: <' . $it['uri'] . '>' . "\n";
422
423                                                 if($it['uri'] !== $it['parent-uri']) {
424                                                         $header .= 'References: <' . $it['parent-uri'] . '>' . "\n";
425                                                         if(! strlen($it['title'])) {
426                                                                 $r = q("SELECT `title` FROM `item` WHERE `parent-uri` = '%s' LIMIT 1",
427                                                                         dbesc($it['parent-uri'])
428                                                                 );
429                                                                 if(count($r)) {
430                                                                         $subtitle = $r[0]['title'];
431                                                                         if($subtitle) {
432                                                                                 if(strncasecmp($subtitle,'RE:',3))
433                                                                                         $subject = $subtitle;
434                                                                                 else
435                                                                                         $subject = 'Re: ' . $subtitle;
436                                                                         }
437                                                                 }
438                                                         }
439                                                 }
440
441                                                 $headers .= 'MIME-Version: 1.0' . "\n";
442                                                 $headers .= 'Content-Type: text/html; charset=UTF-8' . "\n";
443                                                 $headers .= 'Content-Transfer-Encoding: 8bit' . "\n\n";
444                                                 $html    = prepare_body($it);
445                                                 $message = '<html><body>' . $html . '</body></html>';
446                                                 logger('notifier: email delivery to ' . $addr);
447                                                 mail($addr, $subject, $message, $headers);
448                                         }
449                                         break;
450                                 case 'dspr':
451                                 case 'feed':
452                                 case 'face':
453                                 default:
454                                         break;
455                         }
456                 }
457         }
458                 
459         // send additional slaps to mentioned remote tags (@foo@example.com)
460
461         if($slap && count($url_recipients) && $followup && $notify_hub && (! $expire)) {
462                 foreach($url_recipients as $url) {
463                         if($url) {
464                                 logger('notifier: urldelivery: ' . $url);
465                                 $deliver_status = slapper($owner,$url,$slap);
466                                 // TODO: redeliver/queue these items on failure, though there is no contact record
467                         }
468                 }
469         }
470
471         if((strlen($hub)) && ($notify_hub)) {
472                 $hubs = explode(',', $hub);
473                 if(count($hubs)) {
474                         foreach($hubs as $h) {
475                                 $h = trim($h);
476                                 if(! strlen($h))
477                                         continue;
478                                 $params = 'hub.mode=publish&hub.url=' . urlencode($a->get_baseurl() . '/dfrn_poll/' . $owner['nickname'] );
479                                 post_url($h,$params);
480                                 logger('pubsub: publish: ' . $h . ' ' . $params . ' returned ' . $a->get_curl_code());
481                                 if(count($hubs) > 1)
482                                         sleep(7);                               // try and avoid multiple hubs responding at precisely the same time
483                         }
484                 }
485         }
486
487         if($notify_hub) {
488
489                 /**
490                  *
491                  * If you have less than 150 dfrn friends and it's a public message,
492                  * we'll just go ahead and push them out securely with dfrn/rino.
493                  * If you've got more than that, you'll have to rely on PuSH delivery.
494                  *
495                  */
496
497                 $max_allowed = ((get_config('system','maxpubdeliver') === false) ? 150 : intval(get_config('system','maxpubdeliver')));
498                                 
499                 /**
500                  *
501                  * Only get the bare essentials and go back for the full record. 
502                  * If you've got a lot of friends and we grab all the details at once it could exhaust memory. 
503                  *
504                  */
505
506                 $r = q("SELECT `id`, `name` FROM `contact` 
507                         WHERE `network` = 'dfrn' AND `uid` = %d AND `blocked` = 0 AND `pending` = 0
508                         AND `rel` != %d ",
509                         intval($owner['uid']),
510                         intval(REL_FAN)
511                 );
512
513                 if((count($r)) && (($max_allowed == 0) || (count($r) < $max_allowed))) {
514
515                         foreach($r as $rr) {
516
517                                 /* Don't deliver to folks who have already been delivered to */
518
519                                 if(! in_array($rr['id'], $conversants)) {
520                                         $n = q("SELECT * FROM `contact` WHERE `id` = %d LIMIT 1",
521                                                         intval($rr['id'])
522                                         );
523
524                                         if(count($n)) {
525                                         
526                                                 logger('notifier: dfrnpubdelivery: ' . $n[0]['name']);
527                                                 $deliver_status = dfrn_deliver($owner,$n[0],$atom);
528                                         }
529                                 }
530                                 else
531                                         logger('notifier: dfrnpubdelivery: ignoring ' . $rr['name']);
532                         }
533                 }
534         }
535
536         return;
537 }
538
539 if (array_search(__file__,get_included_files())===0){
540   echo "run!";
541   notifier_run($argv,$argc);
542   killme();
543 }