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