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