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