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