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