]> git.mxchange.org Git - friendica.git/blob - include/notifier.php
Merge pull request #3281 from annando/issue-3206-2957
[friendica.git] / include / notifier.php
1 <?php
2
3 use \Friendica\Core\Config;
4
5 require_once('include/queue_fn.php');
6 require_once('include/html2plain.php');
7 require_once('include/Scrape.php');
8 require_once('include/diaspora.php');
9 require_once('include/ostatus.php');
10 require_once('include/salmon.php');
11
12 /*
13  * This file was at one time responsible for doing all deliveries, but this caused
14  * big problems when the process was killed or stalled during the delivery process.
15  * It now invokes separate queues that are delivering via delivery.php and pubsubpublish.php.
16  */
17
18 /*
19  * The notifier is typically called with:
20  *
21  *              proc_run(PRIORITY_HIGH, "include/notifier.php", COMMAND, ITEM_ID);
22  *
23  * where COMMAND is one of the following:
24  *
25  *              activity                                (in diaspora.php, dfrn_confirm.php, profiles.php)
26  *              comment-import                  (in diaspora.php, items.php)
27  *              comment-new                             (in item.php)
28  *              drop                                    (in diaspora.php, items.php, photos.php)
29  *              edit_post                               (in item.php)
30  *              event                                   (in events.php)
31  *              expire                                  (in items.php)
32  *              like                                    (in like.php, poke.php)
33  *              mail                                    (in message.php)
34  *              suggest                                 (in fsuggest.php)
35  *              tag                                             (in photos.php, poke.php, tagger.php)
36  *              tgroup                                  (in items.php)
37  *              wall-new                                (in photos.php, item.php)
38  *              removeme                                (in Contact.php)
39  *              relocate                                (in uimport.php)
40  *
41  * and ITEM_ID is the id of the item in the database that needs to be sent to others.
42  */
43
44
45 function notifier_run(&$argv, &$argc){
46         global $a;
47
48         require_once('include/datetime.php');
49         require_once('include/items.php');
50         require_once('include/bbcode.php');
51         require_once('include/email.php');
52
53         if ($argc < 3) {
54                 return;
55         }
56
57         logger('notifier: invoked: ' . print_r($argv,true), LOGGER_DEBUG);
58
59         $cmd = $argv[1];
60
61         switch($cmd) {
62                 case 'mail':
63                 default:
64                         $item_id = intval($argv[2]);
65                         if (! $item_id) {
66                                 return;
67                         }
68                         break;
69         }
70
71         $expire = false;
72         $mail = false;
73         $fsuggest = false;
74         $relocate = false;
75         $top_level = false;
76         $recipients = array();
77         $url_recipients = array();
78
79         $normal_mode = true;
80
81         if ($cmd === 'mail') {
82                 $normal_mode = false;
83                 $mail = true;
84                 $message = q("SELECT * FROM `mail` WHERE `id` = %d LIMIT 1",
85                                 intval($item_id)
86                 );
87                 if (! count($message)) {
88                         return;
89                 }
90                 $uid = $message[0]['uid'];
91                 $recipients[] = $message[0]['contact-id'];
92                 $item = $message[0];
93
94         } elseif ($cmd === 'expire') {
95                 $normal_mode = false;
96                 $expire = true;
97                 $items = q("SELECT * FROM `item` WHERE `uid` = %d AND `wall` = 1
98                         AND `deleted` = 1 AND `changed` > UTC_TIMESTAMP() - INTERVAL 10 MINUTE",
99                         intval($item_id)
100                 );
101                 $uid = $item_id;
102                 $item_id = 0;
103                 if (! count($items)) {
104                         return;
105                 }
106         } elseif ($cmd === 'suggest') {
107                 $normal_mode = false;
108                 $fsuggest = true;
109
110                 $suggest = q("SELECT * FROM `fsuggest` WHERE `id` = %d LIMIT 1",
111                         intval($item_id)
112                 );
113                 if (! count($suggest)) {
114                         return;
115                 }
116                 $uid = $suggest[0]['uid'];
117                 $recipients[] = $suggest[0]['cid'];
118                 $item = $suggest[0];
119         } elseif ($cmd === 'removeme') {
120                 $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
121                                 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
122                                 `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`, `user`.`guid`
123                         FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
124                                 WHERE `contact`.`uid` = %d AND `contact`.`self` LIMIT 1",
125                                 intval($item_id));
126                 if (!$r)
127                         return;
128
129                 $user = $r[0];
130
131                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `self` LIMIT 1", intval($item_id));
132                 if (!$r)
133                         return;
134
135                 $self = $r[0];
136
137                 $r = q("SELECT * FROM `contact` WHERE NOT `self` AND `uid` = %d", intval($item_id));
138                 if (!$r) {
139                         return;
140                 }
141                 require_once('include/Contact.php');
142                 foreach ($r as $contact) {
143                         terminate_friendship($user, $self, $contact);
144                 }
145                 return;
146         } elseif ($cmd === 'relocate') {
147                 $normal_mode = false;
148                 $relocate = true;
149                 $uid = $item_id;
150
151                 $recipients_relocate = q("SELECT * FROM contact WHERE uid = %d  AND self = 0 AND network = '%s'" , intval($uid), NETWORK_DFRN);
152         } else {
153                 // find ancestors
154                 $r = q("SELECT * FROM `item` WHERE `id` = %d and visible = 1 and moderated = 0 LIMIT 1",
155                         intval($item_id)
156                 );
157
158                 if ((! dbm::is_result($r)) || (! intval($r[0]['parent']))) {
159                         return;
160                 }
161
162                 $target_item = $r[0];
163                 $parent_id = intval($r[0]['parent']);
164                 $uid = $r[0]['uid'];
165                 $updated = $r[0]['edited'];
166
167                 $items = q("SELECT `item`.*, `sign`.`signed_text`,`sign`.`signature`,`sign`.`signer`
168                         FROM `item` LEFT JOIN `sign` ON `sign`.`iid` = `item`.`id` WHERE `parent` = %d and visible = 1 and moderated = 0 ORDER BY `id` ASC",
169                         intval($parent_id)
170                 );
171
172                 if (! count($items)) {
173                         return;
174                 }
175
176                 // avoid race condition with deleting entries
177
178                 if ($items[0]['deleted']) {
179                         foreach ($items as $item) {
180                                 $item['deleted'] = 1;
181                         }
182                 }
183
184                 if ((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
185                         logger('notifier: top level post');
186                         $top_level = true;
187                 }
188
189         }
190
191         $r = q("SELECT `contact`.*, `user`.`pubkey` AS `upubkey`, `user`.`prvkey` AS `uprvkey`,
192                 `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
193                 `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`
194                 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
195                 WHERE `contact`.`uid` = %d AND `contact`.`self` = 1 LIMIT 1",
196                 intval($uid)
197         );
198
199         if (! dbm::is_result($r)) {
200                 return;
201         }
202
203         $owner = $r[0];
204
205         $walltowall = ((($top_level) && ($owner['id'] != $items[0]['contact-id'])) ? true : false);
206
207         $hub = get_config('system','huburl');
208
209         // Should the post be transmitted to Diaspora?
210         $diaspora_delivery = true;
211
212         // If this is a public conversation, notify the feed hub
213         $public_message = true;
214
215         // Do a PuSH
216         $push_notify = false;
217
218         // fill this in with a single salmon slap if applicable
219         $slap = '';
220
221         if (! ($mail || $fsuggest || $relocate)) {
222
223                 $slap = ostatus::salmon($target_item,$owner);
224
225                 require_once('include/group.php');
226
227                 $parent = $items[0];
228
229                 $thr_parent = q("SELECT `network`, `author-link`, `owner-link` FROM `item` WHERE `uri` = '%s' AND `uid` = %d",
230                         dbesc($target_item["thr-parent"]), intval($target_item["uid"]));
231
232                 logger('GUID: '.$target_item["guid"].': Parent is '.$parent['network'].'. Thread parent is '.$thr_parent[0]['network'], LOGGER_DEBUG);
233
234                 // This is IMPORTANT!!!!
235
236                 // We will only send a "notify owner to relay" or followup message if the referenced post
237                 // originated on our system by virtue of having our hostname somewhere
238                 // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
239
240                 // if $parent['wall'] == 1 we will already have the parent message in our array
241                 // and we will relay the whole lot.
242
243                 // expire sends an entire group of expire messages and cannot be forwarded.
244                 // However the conversation owner will be a part of the conversation and will
245                 // be notified during this run.
246                 // Other DFRN conversation members will be alerted during polled updates.
247
248
249
250                 // Diaspora members currently are not notified of expirations, and other networks have
251                 // either limited or no ability to process deletions. We should at least fix Diaspora
252                 // by stringing togther an array of retractions and sending them onward.
253
254
255                 $localhost = str_replace('www.','',$a->get_hostname());
256                 if (strpos($localhost,':')) {
257                         $localhost = substr($localhost,0,strpos($localhost,':'));
258                 }
259                 /**
260                  *
261                  * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
262                  * have been known to cause runaway conditions which affected several servers, along with
263                  * permissions issues.
264                  *
265                  */
266
267                 $relay_to_owner = false;
268
269                 if (!$top_level && ($parent['wall'] == 0) && !$expire && (stristr($target_item['uri'],$localhost))) {
270                         $relay_to_owner = true;
271                 }
272
273
274                 if (($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && !$top_level) {
275                         $relay_to_owner = true;
276                 }
277
278                 // until the 'origin' flag has been in use for several months
279                 // we will just use it as a fallback test
280                 // later we will be able to use it as the primary test of whether or not to relay.
281
282                 if (! $target_item['origin']) {
283                         $relay_to_owner = false;
284                 }
285                 if ($parent['origin']) {
286                         $relay_to_owner = false;
287                 }
288                 if ($relay_to_owner) {
289                         logger('notifier: followup '.$target_item["guid"], LOGGER_DEBUG);
290                         // local followup to remote post
291                         $followup = true;
292                         $public_message = false; // not public
293                         $conversant_str = dbesc($parent['contact-id']);
294                         $recipients = array($parent['contact-id']);
295                         $recipients_followup  = array($parent['contact-id']);
296
297                         //if (!$target_item['private'] AND $target_item['wall'] AND
298                         if (!$target_item['private'] AND
299                                 (strlen($target_item['allow_cid'].$target_item['allow_gid'].
300                                         $target_item['deny_cid'].$target_item['deny_gid']) == 0))
301                                 $push_notify = true;
302
303                         if (($thr_parent AND ($thr_parent[0]['network'] == NETWORK_OSTATUS)) OR ($parent['network'] == NETWORK_OSTATUS)) {
304
305                                 $push_notify = true;
306
307                                 if ($parent["network"] == NETWORK_OSTATUS) {
308                                         // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
309                                         // Currently it is work at progress
310                                         $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s' AND NOT `blocked` AND NOT `pending` AND NOT `archive`",
311                                                 intval($uid),
312                                                 dbesc(NETWORK_DFRN)
313                                         );
314                                         if (dbm::is_result($r)) {
315                                                 foreach ($r as $rr) {
316                                                         $recipients_followup[] = $rr['id'];
317                                                 }
318                                         }
319                                 }
320                         }
321                         logger("Notify ".$target_item["guid"]." via PuSH: ".($push_notify?"Yes":"No"), LOGGER_DEBUG);
322                 } else {
323                         $followup = false;
324
325                         logger('Distributing directly '.$target_item["guid"], LOGGER_DEBUG);
326
327                         // don't send deletions onward for other people's stuff
328
329                         if ($target_item['deleted'] && (! intval($target_item['wall']))) {
330                                 logger('notifier: ignoring delete notification for non-wall item');
331                                 return;
332                         }
333
334                         if ((strlen($parent['allow_cid']))
335                                 || (strlen($parent['allow_gid']))
336                                 || (strlen($parent['deny_cid']))
337                                 || (strlen($parent['deny_gid']))) {
338                                 $public_message = false; // private recipients, not public
339                         }
340
341                         $allow_people = expand_acl($parent['allow_cid']);
342                         $allow_groups = expand_groups(expand_acl($parent['allow_gid']),true);
343                         $deny_people  = expand_acl($parent['deny_cid']);
344                         $deny_groups  = expand_groups(expand_acl($parent['deny_gid']));
345
346                         // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
347                         // a delivery fork. private groups (forum_mode == 2) do not uplink
348
349                         if ((intval($parent['forum_mode']) == 1) && (! $top_level) && ($cmd !== 'uplink')) {
350                                 proc_run(PRIORITY_HIGH,'include/notifier.php','uplink',$item_id);
351                         }
352
353                         $conversants = array();
354
355                         foreach ($items as $item) {
356                                 $recipients[] = $item['contact-id'];
357                                 $conversants[] = $item['contact-id'];
358                                 // pull out additional tagged people to notify (if public message)
359                                 if ($public_message && strlen($item['inform'])) {
360                                         $people = explode(',',$item['inform']);
361                                         foreach ($people as $person) {
362                                                 if (substr($person,0,4) === 'cid:') {
363                                                         $recipients[] = intval(substr($person,4));
364                                                         $conversants[] = intval(substr($person,4));
365                                                 } else {
366                                                         $url_recipients[] = substr($person,4);
367                                                 }
368                                         }
369                                 }
370                         }
371
372                         if (count($url_recipients))
373                                 logger('notifier: '.$target_item["guid"].' url_recipients ' . print_r($url_recipients,true));
374
375                         $conversants = array_unique($conversants);
376
377
378                         $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
379                         $deny = array_unique(array_merge($deny_people,$deny_groups));
380                         $recipients = array_diff($recipients,$deny);
381
382                         $conversant_str = dbesc(implode(', ',$conversants));
383                 }
384
385                 // If the thread parent is OStatus then do some magic to distribute the messages.
386                 // We have not only to look at the parent, since it could be a Friendica thread.
387                 if (($thr_parent AND ($thr_parent[0]['network'] == NETWORK_OSTATUS)) OR ($parent['network'] == NETWORK_OSTATUS)) {
388
389                         $diaspora_delivery = false;
390
391                         logger('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent[0]['author-link']." - Owner: ".$thr_parent[0]['owner-link'], LOGGER_DEBUG);
392
393                         // Send a salmon to the parent author
394                         $r = q("SELECT `url`, `notify` FROM `contact` WHERE `nurl`='%s' AND `uid` IN (0, %d) AND `notify` != ''",
395                                 dbesc(normalise_link($thr_parent[0]['author-link'])),
396                                 intval($uid));
397                         if (dbm::is_result($r)) {
398                                 $probed_contact = $r[0];
399                         } else {
400                                 $probed_contact = probe_url($thr_parent[0]['author-link']);
401                         }
402
403                         if ($probed_contact["notify"] != "") {
404                                 logger('Notify parent author '.$probed_contact["url"].': '.$probed_contact["notify"]);
405                                 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
406                         }
407
408                         // Send a salmon to the parent owner
409                         $r = q("SELECT `url`, `notify` FROM `contact` WHERE `nurl`='%s' AND `uid` IN (0, %d) AND `notify` != ''",
410                                 dbesc(normalise_link($thr_parent[0]['owner-link'])),
411                                 intval($uid));
412                         if (dbm::is_result($r)) {
413                                 $probed_contact = $r[0];
414                         } else {
415                                 $probed_contact = probe_url($thr_parent[0]['owner-link']);
416                         }
417
418                         if ($probed_contact["notify"] != "") {
419                                 logger('Notify parent owner '.$probed_contact["url"].': '.$probed_contact["notify"]);
420                                 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
421                         }
422
423                         // Send a salmon notification to every person we mentioned in the post
424                         $arr = explode(',',$target_item['tag']);
425                         foreach ($arr as $x) {
426                                 //logger('Checking tag '.$x, LOGGER_DEBUG);
427                                 $matches = null;
428                                 if (preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
429                                                 $probed_contact = probe_url($matches[1]);
430                                         if ($probed_contact["notify"] != "") {
431                                                 logger('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
432                                                 $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
433                                         }
434                                 }
435                         }
436
437                         // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
438                         $sql_extra = " AND `network` IN ('".NETWORK_OSTATUS."', '".NETWORK_DFRN."')";
439                 } else {
440                         $sql_extra = " AND `network` IN ('".NETWORK_OSTATUS."', '".NETWORK_DFRN."', '".NETWORK_DIASPORA."', '".NETWORK_MAIL."', '".NETWORK_MAIL2."')";
441                 }
442         } else {
443                 $public_message = false;
444         }
445
446         // If this is a public message and pubmail is set on the parent, include all your email contacts
447
448         $mail_disabled = ((function_exists('imap_open') && (! get_config('system','imap_disabled'))) ? 0 : 1);
449
450         if (! $mail_disabled) {
451                 if ((! strlen($target_item['allow_cid'])) && (! strlen($target_item['allow_gid']))
452                         && (! strlen($target_item['deny_cid'])) && (! strlen($target_item['deny_gid']))
453                         && (intval($target_item['pubmail']))) {
454                         $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
455                                 intval($uid),
456                                 dbesc(NETWORK_MAIL)
457                         );
458                         if (dbm::is_result($r)) {
459                                 foreach ($r as $rr) {
460                                         $recipients[] = $rr['id'];
461                                 }
462                         }
463                 }
464         }
465
466         if ($followup) {
467                 $recip_str = implode(', ', $recipients_followup);
468         } else {
469                 $recip_str = implode(', ', $recipients);
470         }
471         if ($relocate) {
472                 $r = $recipients_relocate;
473         } else {
474                 $r = q("SELECT `id`, `url`, `network`, `self` FROM `contact`
475                         WHERE `id` IN (%s) AND NOT `blocked` AND NOT `pending` AND NOT `archive`".$sql_extra,
476                         dbesc($recip_str)
477                 );
478         }
479
480         // delivery loop
481
482         if (dbm::is_result($r)) {
483                 foreach ($r as $contact) {
484                         if ($contact['self']) {
485                                 continue;
486                         }
487                         logger("Deliver ".$target_item["guid"]." to ".$contact['url']." via network ".$contact['network'], LOGGER_DEBUG);
488
489                         proc_run(PRIORITY_HIGH,'include/delivery.php', $cmd, $item_id, $contact['id']);
490                 }
491         }
492
493         // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
494         // They are especially used for notifications to OStatus users that don't follow us.
495
496         if ($slap && count($url_recipients) && ($public_message || $push_notify) && $normal_mode) {
497                 if (!get_config('system','dfrn_only')) {
498                         foreach ($url_recipients as $url) {
499                                 if ($url) {
500                                         logger('notifier: urldelivery: ' . $url);
501                                         $deliver_status = slapper($owner,$url,$slap);
502                                         /// @TODO Redeliver/queue these items on failure, though there is no contact record
503                                 }
504                         }
505                 }
506         }
507
508
509         if ($public_message) {
510
511                 $r0 = array();
512                 $r1 = array();
513
514                 if ($diaspora_delivery) {
515                         if (!$followup) {
516                                 $r0 = Diaspora::relay_list();
517                         }
518
519                         $r1 = q("SELECT DISTINCT(`batch`), `id`, `name`,`network` FROM `contact` WHERE `network` = '%s'
520                                 AND `uid` = %d AND `rel` != %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` GROUP BY `batch` ORDER BY rand()",
521                                 dbesc(NETWORK_DIASPORA),
522                                 intval($owner['uid']),
523                                 intval(CONTACT_IS_SHARING)
524                         );
525                 }
526
527                 $r2 = q("SELECT `id`, `name`,`network` FROM `contact`
528                         WHERE `network` in ( '%s', '%s')  AND `uid` = %d AND NOT `blocked` AND NOT `pending` AND NOT `archive`
529                         AND `rel` != %d order by rand() ",
530                         dbesc(NETWORK_DFRN),
531                         dbesc(NETWORK_MAIL2),
532                         intval($owner['uid']),
533                         intval(CONTACT_IS_SHARING)
534                 );
535
536                 $r = array_merge($r2,$r1,$r0);
537
538                 if (dbm::is_result($r)) {
539                         logger('pubdeliver '.$target_item["guid"].': '.print_r($r,true), LOGGER_DEBUG);
540
541                         foreach ($r as $rr) {
542
543                                 // except for Diaspora batch jobs
544                                 // Don't deliver to folks who have already been delivered to
545
546                                 if (($rr['network'] !== NETWORK_DIASPORA) && (in_array($rr['id'],$conversants))) {
547                                         logger('notifier: already delivered id=' . $rr['id']);
548                                         continue;
549                                 }
550
551                                 if ((! $mail) && (! $fsuggest) && (! $followup)) {
552                                         logger('notifier: delivery agent: '.$rr['name'].' '.$rr['id'].' '.$rr['network'].' '.$target_item["guid"]);
553                                         proc_run(PRIORITY_HIGH,'include/delivery.php',$cmd,$item_id,$rr['id']);
554                                 }
555                         }
556                 }
557
558                 $push_notify = true;
559
560         }
561
562         // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
563         if ($push_notify AND strlen($hub)) {
564                 $hubs = explode(',', $hub);
565                 if (count($hubs)) {
566                         foreach ($hubs as $h) {
567                                 $h = trim($h);
568                                 if (! strlen($h)) {
569                                         continue;
570                                 }
571
572                                 if ($h === '[internal]') {
573                                         // Set push flag for PuSH subscribers to this topic,
574                                         // they will be notified in queue.php
575                                         q("UPDATE `push_subscriber` SET `push` = 1 ".
576                                           "WHERE `nickname` = '%s' AND `push` = 0", dbesc($owner['nickname']));
577
578                                         logger('Activating internal PuSH for item '.$item_id, LOGGER_DEBUG);
579
580                                 } else {
581
582                                         $params = 'hub.mode=publish&hub.url=' . urlencode( App::get_baseurl() . '/dfrn_poll/' . $owner['nickname'] );
583                                         post_url($h,$params);
584                                         logger('publish for item '.$item_id.' ' . $h . ' ' . $params . ' returned ' . $a->get_curl_code());
585                                 }
586                                 if (count($hubs) > 1) {
587                                         sleep(7);                               // try and avoid multiple hubs responding at precisely the same time
588                                 }
589                         }
590                 }
591
592                 // Handling the pubsubhubbub requests
593                 proc_run(PRIORITY_HIGH,'include/pubsubpublish.php');
594         }
595
596         logger('notifier: calling hooks', LOGGER_DEBUG);
597
598         if ($normal_mode) {
599                 call_hooks('notifier_normal',$target_item);
600         }
601
602         call_hooks('notifier_end',$target_item);
603
604         return;
605 }