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