]> git.mxchange.org Git - friendica.git/blob - src/Worker/Notifier.php
Account deletion could work now.
[friendica.git] / src / Worker / Notifier.php
1 <?php
2 /**
3  * @file src/Worker/Notifier.php
4  */
5 namespace Friendica\Worker;
6
7 use Friendica\BaseObject;
8 use Friendica\Core\Addon;
9 use Friendica\Core\Config;
10 use Friendica\Core\Protocol;
11 use Friendica\Core\Worker;
12 use Friendica\Database\DBA;
13 use Friendica\Model\Contact;
14 use Friendica\Model\Group;
15 use Friendica\Model\Item;
16 use Friendica\Model\PushSubscriber;
17 use Friendica\Model\User;
18 use Friendica\Network\Probe;
19 use Friendica\Protocol\ActivityPub;
20 use Friendica\Protocol\Diaspora;
21 use Friendica\Protocol\OStatus;
22 use Friendica\Protocol\Salmon;
23
24 require_once 'include/dba.php';
25 require_once 'include/items.php';
26
27 /*
28  * The notifier is typically called with:
29  *
30  *              Worker::add(PRIORITY_HIGH, "Notifier", COMMAND, ITEM_ID);
31  *
32  * where COMMAND is one of the following:
33  *
34  *              activity                                (in diaspora.php, dfrn_confirm.php, profiles.php)
35  *              comment-import                  (in diaspora.php, items.php)
36  *              comment-new                             (in item.php)
37  *              drop                                    (in diaspora.php, items.php, photos.php)
38  *              edit_post                               (in item.php)
39  *              event                                   (in events.php)
40  *              like                                    (in like.php, poke.php)
41  *              mail                                    (in message.php)
42  *              suggest                                 (in fsuggest.php)
43  *              tag                                             (in photos.php, poke.php, tagger.php)
44  *              tgroup                                  (in items.php)
45  *              wall-new                                (in photos.php, item.php)
46  *              removeme                                (in Contact.php)
47  *              relocate                                (in uimport.php)
48  *
49  * and ITEM_ID is the id of the item in the database that needs to be sent to others.
50  */
51
52 class Notifier
53 {
54         public static function execute($cmd, $item_id)
55         {
56                 $a = BaseObject::getApp();
57
58                 logger('notifier: invoked: '.$cmd.': '.$item_id, LOGGER_DEBUG);
59
60                 $top_level = false;
61                 $recipients = [];
62                 $url_recipients = [];
63
64                 $normal_mode = true;
65                 $recipients_relocate = [];
66
67                 if ($cmd == Delivery::MAIL) {
68                         $normal_mode = false;
69                         $message = DBA::selectFirst('mail', ['uid', 'contact-id'], ['id' => $item_id]);
70                         if (!DBA::isResult($message)) {
71                                 return;
72                         }
73                         $uid = $message['uid'];
74                         $recipients[] = $message['contact-id'];
75                 } elseif ($cmd == Delivery::SUGGESTION) {
76                         $normal_mode = false;
77                         $suggest = DBA::selectFirst('fsuggest', ['uid', 'cid'], ['id' => $item_id]);
78                         if (!DBA::isResult($suggest)) {
79                                 return;
80                         }
81                         $uid = $suggest['uid'];
82                         $recipients[] = $suggest['cid'];
83                 } elseif ($cmd == Delivery::REMOVAL) {
84                         $r = q("SELECT `contact`.*, `user`.`prvkey` AS `uprvkey`,
85                                         `user`.`timezone`, `user`.`nickname`, `user`.`sprvkey`, `user`.`spubkey`,
86                                         `user`.`page-flags`, `user`.`prvnets`, `user`.`account-type`, `user`.`guid`
87                                 FROM `contact` INNER JOIN `user` ON `user`.`uid` = `contact`.`uid`
88                                         WHERE `contact`.`uid` = %d AND `contact`.`self` LIMIT 1",
89                                         intval($item_id));
90                         if (!$r) {
91                                 return;
92                         }
93                         $user = $r[0];
94
95                         $r = q("SELECT * FROM `contact` WHERE NOT `self` AND `uid` = %d", intval($item_id));
96                         if (!$r) {
97                                 return;
98                         }
99                         foreach ($r as $contact) {
100                                 Contact::terminateFriendship($user, $contact, true);
101                         }
102
103                         $inboxes = ActivityPub::fetchTargetInboxesforUser(0);
104                         foreach ($inboxes as $inbox) {
105                                 logger('Account removal for user ' . $uid . ' to ' . $inbox .' via ActivityPub', LOGGER_DEBUG);
106                                 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
107                                         'APDelivery', Delivery::REMOVAL, '', $inbox, $uid);
108                         }
109
110                         return;
111                 } elseif ($cmd == Delivery::RELOCATION) {
112                         $normal_mode = false;
113                         $uid = $item_id;
114
115                         $recipients_relocate = q("SELECT * FROM `contact` WHERE `uid` = %d AND NOT `self` AND `network` IN ('%s', '%s')",
116                                                 intval($uid), Protocol::DFRN, Protocol::DIASPORA);
117                 } else {
118                         // find ancestors
119                         $condition = ['id' => $item_id, 'visible' => true, 'moderated' => false];
120                         $target_item = Item::selectFirst([], $condition);
121
122                         if (!DBA::isResult($target_item) || !intval($target_item['parent'])) {
123                                 return;
124                         }
125
126                         $parent_id = intval($target_item['parent']);
127                         $uid = $target_item['contact-uid'];
128                         $updated = $target_item['edited'];
129
130                         $condition = ['parent' => $parent_id, 'visible' => true, 'moderated' => false];
131                         $params = ['order' => ['id']];
132                         $ret = Item::select([], $condition, $params);
133
134                         if (!DBA::isResult($ret)) {
135                                 return;
136                         }
137
138                         $items = Item::inArray($ret);
139
140                         // avoid race condition with deleting entries
141                         if ($items[0]['deleted']) {
142                                 foreach ($items as $item) {
143                                         $item['deleted'] = 1;
144                                 }
145                         }
146
147                         if ((count($items) == 1) && ($items[0]['id'] === $target_item['id']) && ($items[0]['uri'] === $items[0]['parent-uri'])) {
148                                 logger('notifier: top level post');
149                                 $top_level = true;
150                         }
151                 }
152
153                 $owner = User::getOwnerDataById($uid);
154                 if (!$owner) {
155                         return;
156                 }
157
158                 $walltowall = ($top_level && ($owner['id'] != $items[0]['contact-id']) ? true : false);
159
160                 // Should the post be transmitted to Diaspora?
161                 $diaspora_delivery = true;
162
163                 // If this is a public conversation, notify the feed hub
164                 $public_message = true;
165
166                 // Do a PuSH
167                 $push_notify = false;
168
169                 // Deliver directly to a forum, don't PuSH
170                 $direct_forum_delivery = false;
171
172                 $followup = false;
173                 $recipients_followup = [];
174                 $conversants = [];
175
176                 if (!in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION, Delivery::RELOCATION])) {
177                         $parent = $items[0];
178
179                         $fields = ['network', 'author-id', 'owner-id'];
180                         $condition = ['uri' => $target_item["thr-parent"], 'uid' => $target_item["uid"]];
181                         $thr_parent = Item::selectFirst($fields, $condition);
182
183                         logger('GUID: '.$target_item["guid"].': Parent is '.$parent['network'].'. Thread parent is '.$thr_parent['network'], LOGGER_DEBUG);
184
185                         // This is IMPORTANT!!!!
186
187                         // We will only send a "notify owner to relay" or followup message if the referenced post
188                         // originated on our system by virtue of having our hostname somewhere
189                         // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
190
191                         // if $parent['wall'] == 1 we will already have the parent message in our array
192                         // and we will relay the whole lot.
193
194                         $localhost = str_replace('www.','',$a->get_hostname());
195                         if (strpos($localhost,':')) {
196                                 $localhost = substr($localhost,0,strpos($localhost,':'));
197                         }
198                         /**
199                          *
200                          * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
201                          * have been known to cause runaway conditions which affected several servers, along with
202                          * permissions issues.
203                          *
204                          */
205
206                         $relay_to_owner = false;
207
208                         if (!$top_level && ($parent['wall'] == 0) && (stristr($target_item['uri'],$localhost))) {
209                                 $relay_to_owner = true;
210                         }
211
212
213                         if (($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && !$top_level) {
214                                 $relay_to_owner = true;
215                         }
216
217                         // until the 'origin' flag has been in use for several months
218                         // we will just use it as a fallback test
219                         // later we will be able to use it as the primary test of whether or not to relay.
220
221                         if (!$target_item['origin']) {
222                                 $relay_to_owner = false;
223                         }
224                         if ($parent['origin']) {
225                                 $relay_to_owner = false;
226                         }
227
228                         // Special treatment for forum posts
229                         if (self::isForumPost($target_item, $owner)) {
230                                 $relay_to_owner = true;
231                                 $direct_forum_delivery = true;
232                         }
233
234                         // Avoid that comments in a forum thread are sent to OStatus
235                         if (self::isForumPost($parent, $owner)) {
236                                 $direct_forum_delivery = true;
237                         }
238
239                         if ($relay_to_owner) {
240                                 // local followup to remote post
241                                 $followup = true;
242                                 $public_message = false; // not public
243                                 $conversant_str = DBA::escape($parent['contact-id']);
244                                 $recipients = [$parent['contact-id']];
245                                 $recipients_followup  = [$parent['contact-id']];
246
247                                 logger('notifier: followup '.$target_item["guid"].' to '.$conversant_str, LOGGER_DEBUG);
248
249                                 //if (!$target_item['private'] && $target_item['wall'] &&
250                                 if (!$target_item['private'] &&
251                                         (strlen($target_item['allow_cid'].$target_item['allow_gid'].
252                                                 $target_item['deny_cid'].$target_item['deny_gid']) == 0))
253                                         $push_notify = true;
254
255                                 if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
256                                         $push_notify = true;
257
258                                         if ($parent["network"] == Protocol::OSTATUS) {
259                                                 // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
260                                                 // Currently it is work at progress
261                                                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s' AND NOT `blocked` AND NOT `pending` AND NOT `archive`",
262                                                         intval($uid),
263                                                         DBA::escape(Protocol::DFRN)
264                                                 );
265                                                 if (DBA::isResult($r)) {
266                                                         foreach ($r as $rr) {
267                                                                 $recipients_followup[] = $rr['id'];
268                                                         }
269                                                 }
270                                         }
271                                 }
272
273                                 if ($direct_forum_delivery) {
274                                         $push_notify = false;
275                                 }
276
277                                 logger("Notify ".$target_item["guid"]." via PuSH: ".($push_notify?"Yes":"No"), LOGGER_DEBUG);
278                         } else {
279                                 $followup = false;
280
281                                 logger('Distributing directly '.$target_item["guid"], LOGGER_DEBUG);
282
283                                 // don't send deletions onward for other people's stuff
284
285                                 if ($target_item['deleted'] && !intval($target_item['wall'])) {
286                                         logger('notifier: ignoring delete notification for non-wall item');
287                                         return;
288                                 }
289
290                                 if (strlen($parent['allow_cid'])
291                                         || strlen($parent['allow_gid'])
292                                         || strlen($parent['deny_cid'])
293                                         || strlen($parent['deny_gid'])) {
294                                         $public_message = false; // private recipients, not public
295                                 }
296
297                                 $allow_people = expand_acl($parent['allow_cid']);
298                                 $allow_groups = Group::expand(expand_acl($parent['allow_gid']),true);
299                                 $deny_people  = expand_acl($parent['deny_cid']);
300                                 $deny_groups  = Group::expand(expand_acl($parent['deny_gid']));
301
302                                 // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
303                                 // a delivery fork. private groups (forum_mode == 2) do not uplink
304
305                                 if ((intval($parent['forum_mode']) == 1) && !$top_level && ($cmd !== 'uplink')) {
306                                         Worker::add($a->queue['priority'], 'Notifier', 'uplink', $item_id);
307                                 }
308
309                                 foreach ($items as $item) {
310                                         $recipients[] = $item['contact-id'];
311                                         $conversants[] = $item['contact-id'];
312                                         // pull out additional tagged people to notify (if public message)
313                                         if ($public_message && strlen($item['inform'])) {
314                                                 $people = explode(',',$item['inform']);
315                                                 foreach ($people as $person) {
316                                                         if (substr($person,0,4) === 'cid:') {
317                                                                 $recipients[] = intval(substr($person,4));
318                                                                 $conversants[] = intval(substr($person,4));
319                                                         } else {
320                                                                 $url_recipients[] = substr($person,4);
321                                                         }
322                                                 }
323                                         }
324                                 }
325
326                                 if (count($url_recipients)) {
327                                         logger('notifier: '.$target_item["guid"].' url_recipients ' . print_r($url_recipients,true));
328                                 }
329
330                                 $conversants = array_unique($conversants);
331
332                                 $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
333                                 $deny = array_unique(array_merge($deny_people,$deny_groups));
334                                 $recipients = array_diff($recipients,$deny);
335
336                                 $conversant_str = DBA::escape(implode(', ',$conversants));
337                         }
338
339                         // If the thread parent is OStatus then do some magic to distribute the messages.
340                         // We have not only to look at the parent, since it could be a Friendica thread.
341                         if (($thr_parent && ($thr_parent['network'] == Protocol::OSTATUS)) || ($parent['network'] == Protocol::OSTATUS)) {
342                                 $diaspora_delivery = false;
343
344                                 logger('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent['author-id']." - Owner: ".$thr_parent['owner-id'], LOGGER_DEBUG);
345
346                                 // Send a salmon to the parent author
347                                 $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['author-id']]);
348                                 if (DBA::isResult($probed_contact) && !empty($probed_contact["notify"])) {
349                                         logger('Notify parent author '.$probed_contact["url"].': '.$probed_contact["notify"]);
350                                         $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
351                                 }
352
353                                 // Send a salmon to the parent owner
354                                 $probed_contact = DBA::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['owner-id']]);
355                                 if (DBA::isResult($probed_contact) && !empty($probed_contact["notify"])) {
356                                         logger('Notify parent owner '.$probed_contact["url"].': '.$probed_contact["notify"]);
357                                         $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
358                                 }
359
360                                 // Send a salmon notification to every person we mentioned in the post
361                                 $arr = explode(',',$target_item['tag']);
362                                 foreach ($arr as $x) {
363                                         //logger('Checking tag '.$x, LOGGER_DEBUG);
364                                         $matches = null;
365                                         if (preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
366                                                         $probed_contact = Probe::uri($matches[1]);
367                                                 if ($probed_contact["notify"] != "") {
368                                                         logger('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
369                                                         $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
370                                                 }
371                                         }
372                                 }
373
374                                 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
375                                 $networks = [Protocol::OSTATUS, Protocol::DFRN];
376                         } else {
377                                 $networks = [Protocol::OSTATUS, Protocol::DFRN, Protocol::DIASPORA, Protocol::MAIL];
378                         }
379                 } else {
380                         $public_message = false;
381                 }
382
383                 // If this is a public message and pubmail is set on the parent, include all your email contacts
384                 if (!empty($target_item) && function_exists('imap_open') && !Config::get('system','imap_disabled')) {
385                         if (!strlen($target_item['allow_cid']) && !strlen($target_item['allow_gid'])
386                                 && !strlen($target_item['deny_cid']) && !strlen($target_item['deny_gid'])
387                                 && intval($target_item['pubmail'])) {
388                                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
389                                         intval($uid),
390                                         DBA::escape(Protocol::MAIL)
391                                 );
392                                 if (DBA::isResult($r)) {
393                                         foreach ($r as $rr) {
394                                                 $recipients[] = $rr['id'];
395                                         }
396                                 }
397                         }
398                 }
399
400                 if (($cmd == Delivery::RELOCATION)) {
401                         $r = $recipients_relocate;
402                 } else {
403                         if ($followup) {
404                                 $recipients = $recipients_followup;
405                         }
406                         $condition = ['id' => $recipients, 'self' => false,
407                                 'blocked' => false, 'pending' => false, 'archive' => false];
408                         if (!empty($networks)) {
409                                 $condition['network'] = $networks;
410                         }
411                         $contacts = DBA::select('contact', ['id', 'url', 'network'], $condition);
412                         $r = DBA::toArray($contacts);
413                 }
414
415                 // delivery loop
416                 if (DBA::isResult($r)) {
417                         foreach ($r as $contact) {
418                                 logger("Deliver ".$item_id." to ".$contact['url']." via network ".$contact['network'], LOGGER_DEBUG);
419
420                                 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
421                                                 'Delivery', $cmd, $item_id, (int)$contact['id']);
422                         }
423                 }
424
425                 $inboxes = [];
426
427                 if ($target_item['origin']) {
428                         $inboxes = ActivityPub::fetchTargetInboxes($target_item, $uid);
429                 }
430
431                 if ($parent['origin']) {
432                         $parent_inboxes = ActivityPub::fetchTargetInboxes($parent, $uid);
433                         $inboxes = array_merge($inboxes, $parent_inboxes);
434                 }
435
436                 foreach ($inboxes as $inbox) {
437                         logger('Deliver ' . $item_id .' to ' . $inbox .' via ActivityPub', LOGGER_DEBUG);
438
439                         Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
440                                         'APDelivery', $cmd, $item_id, $inbox, $uid);
441                 }
442
443                 // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
444                 // They are especially used for notifications to OStatus users that don't follow us.
445                 if (!Config::get('system', 'dfrn_only') && count($url_recipients) && ($public_message || $push_notify) && $normal_mode) {
446                         $slap = OStatus::salmon($target_item, $owner);
447                         foreach ($url_recipients as $url) {
448                                 if ($url) {
449                                         logger('notifier: urldelivery: ' . $url);
450                                         $deliver_status = Salmon::slapper($owner, $url, $slap);
451                                         /// @TODO Redeliver/queue these items on failure, though there is no contact record
452                                 }
453                         }
454                 }
455
456                 if ($public_message) {
457                         $r1 = [];
458
459                         if ($diaspora_delivery) {
460                                 $r1 = q("SELECT `batch`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`name`) AS `name`, ANY_VALUE(`network`) AS `network`
461                                         FROM `contact` WHERE `network` = '%s' AND `batch` != ''
462                                         AND `uid` = %d AND `rel` != %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` GROUP BY `batch`",
463                                         DBA::escape(Protocol::DIASPORA),
464                                         intval($owner['uid']),
465                                         intval(Contact::SHARING)
466                                 );
467
468                                 // Fetch the participation list
469                                 // The function will ensure that there are no duplicates
470                                 $r1 = Diaspora::participantsForThread($item_id, $r1);
471
472                                 // Add the relay to the list, avoid duplicates
473                                 if (!$followup) {
474                                         $r1 = Diaspora::relayList($item_id, $r1);
475                                 }
476                         }
477
478                         $condition = ['network' => Protocol::DFRN, 'uid' => $owner['uid'], 'blocked' => false,
479                                 'pending' => false, 'archive' => false, 'rel' => [Contact::FOLLOWER, Contact::FRIEND]];
480
481                         $r2 = DBA::toArray(DBA::select('contact', ['id', 'name', 'network'], $condition));
482
483                         $r = array_merge($r2, $r1);
484
485                         if (DBA::isResult($r)) {
486                                 logger('pubdeliver '.$target_item["guid"].': '.print_r($r,true), LOGGER_DEBUG);
487
488                                 foreach ($r as $rr) {
489                                         // except for Diaspora batch jobs
490                                         // Don't deliver to folks who have already been delivered to
491
492                                         if (($rr['network'] !== Protocol::DIASPORA) && (in_array($rr['id'], $conversants))) {
493                                                 logger('notifier: already delivered id=' . $rr['id']);
494                                                 continue;
495                                         }
496
497                                         if (!in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION]) && !$followup) {
498                                                 logger('notifier: delivery agent: '.$rr['name'].' '.$rr['id'].' '.$rr['network'].' '.$target_item["guid"]);
499                                                 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
500                                                                 'Delivery', $cmd, $item_id, (int)$rr['id']);
501                                         }
502                                 }
503                         }
504
505                         $push_notify = true;
506                 }
507
508                 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
509                 if ($push_notify) {
510                         logger('Activating internal PuSH for item '.$item_id, LOGGER_DEBUG);
511
512                         // Handling the pubsubhubbub requests
513                         PushSubscriber::publishFeed($owner['uid'], $a->queue['priority']);
514                 }
515
516                 logger('notifier: calling hooks for ' . $cmd . ' ' . $item_id, LOGGER_DEBUG);
517
518                 if ($normal_mode) {
519                         Addon::forkHooks($a->queue['priority'], 'notifier_normal', $target_item);
520                 }
521
522                 Addon::callHooks('notifier_end',$target_item);
523
524                 return;
525         }
526
527         private static function isForumPost($item, $owner) {
528                 if (($item['author-id'] == $item['owner-id']) ||
529                         ($owner['id'] == $item['contact-id']) ||
530                         ($item['uri'] != $item['parent-uri'])) {
531                         return false;
532                 }
533
534                 $fields = ['forum', 'prv'];
535                 $condition = ['id' => $item['contact-id']];
536                 $contact = DBA::selectFirst('contact', $fields, $condition);
537                 if (!DBA::isResult($contact)) {
538                         // Should never happen
539                         return false;
540                 }
541
542                 // Is the post from a forum?
543                 return ($contact['forum'] || $contact['prv']);
544         }
545 }