]> git.mxchange.org Git - friendica.git/blob - src/Worker/Notifier.php
API: fix sender/recipient of PMs: check api_user before get user info.
[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                         $fields = ['network', 'author-id', 'owner-id'];
168                         $condition = ['uri' => $target_item["thr-parent"], 'uid' => $target_item["uid"]];
169                         $thr_parent = dba::selectFirst('item', $fields, $condition);
170
171                         logger('GUID: '.$target_item["guid"].': Parent is '.$parent['network'].'. Thread parent is '.$thr_parent['network'], LOGGER_DEBUG);
172
173                         // This is IMPORTANT!!!!
174
175                         // We will only send a "notify owner to relay" or followup message if the referenced post
176                         // originated on our system by virtue of having our hostname somewhere
177                         // in the URI, AND it was a comment (not top_level) AND the parent originated elsewhere.
178
179                         // if $parent['wall'] == 1 we will already have the parent message in our array
180                         // and we will relay the whole lot.
181
182                         $localhost = str_replace('www.','',$a->get_hostname());
183                         if (strpos($localhost,':')) {
184                                 $localhost = substr($localhost,0,strpos($localhost,':'));
185                         }
186                         /**
187                          *
188                          * Be VERY CAREFUL if you make any changes to the following several lines. Seemingly innocuous changes
189                          * have been known to cause runaway conditions which affected several servers, along with
190                          * permissions issues.
191                          *
192                          */
193
194                         $relay_to_owner = false;
195
196                         if (!$top_level && ($parent['wall'] == 0) && (stristr($target_item['uri'],$localhost))) {
197                                 $relay_to_owner = true;
198                         }
199
200
201                         if (($cmd === 'uplink') && (intval($parent['forum_mode']) == 1) && !$top_level) {
202                                 $relay_to_owner = true;
203                         }
204
205                         // until the 'origin' flag has been in use for several months
206                         // we will just use it as a fallback test
207                         // later we will be able to use it as the primary test of whether or not to relay.
208
209                         if (!$target_item['origin']) {
210                                 $relay_to_owner = false;
211                         }
212                         if ($parent['origin']) {
213                                 $relay_to_owner = false;
214                         }
215
216                         // Special treatment for forum posts
217                         if (($target_item['author-id'] != $target_item['owner-id']) &&
218                                 ($owner['id'] != $target_item['contact-id']) &&
219                                 ($target_item['uri'] === $target_item['parent-uri'])) {
220
221                                 $fields = ['forum', 'prv'];
222                                 $condition = ['id' => $target_item['contact-id']];
223                                 $contact = dba::selectFirst('contact', $fields, $condition);
224                                 if (!DBM::is_result($contact)) {
225                                         // Should never happen
226                                         return false;
227                                 }
228
229                                 // Is the post from a forum?
230                                 if ($contact['forum'] || $contact['prv']) {
231                                         $relay_to_owner = true;
232                                         $direct_forum_delivery = true;
233                                 }
234                         }
235                         if ($relay_to_owner) {
236                                 // local followup to remote post
237                                 $followup = true;
238                                 $public_message = false; // not public
239                                 $conversant_str = dbesc($parent['contact-id']);
240                                 $recipients = [$parent['contact-id']];
241                                 $recipients_followup  = [$parent['contact-id']];
242
243                                 logger('notifier: followup '.$target_item["guid"].' to '.$conversant_str, LOGGER_DEBUG);
244
245                                 //if (!$target_item['private'] && $target_item['wall'] &&
246                                 if (!$target_item['private'] &&
247                                         (strlen($target_item['allow_cid'].$target_item['allow_gid'].
248                                                 $target_item['deny_cid'].$target_item['deny_gid']) == 0))
249                                         $push_notify = true;
250
251                                 if (($thr_parent && ($thr_parent['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
252                                         $push_notify = true;
253
254                                         if ($parent["network"] == NETWORK_OSTATUS) {
255                                                 // Distribute the message to the DFRN contacts as if this wasn't a followup since OStatus can't relay comments
256                                                 // Currently it is work at progress
257                                                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s' AND NOT `blocked` AND NOT `pending` AND NOT `archive`",
258                                                         intval($uid),
259                                                         dbesc(NETWORK_DFRN)
260                                                 );
261                                                 if (DBM::is_result($r)) {
262                                                         foreach ($r as $rr) {
263                                                                 $recipients_followup[] = $rr['id'];
264                                                         }
265                                                 }
266                                         }
267                                 }
268
269                                 if ($direct_forum_delivery) {
270                                         $push_notify = false;
271                                 }
272
273                                 logger("Notify ".$target_item["guid"]." via PuSH: ".($push_notify?"Yes":"No"), LOGGER_DEBUG);
274                         } else {
275                                 $followup = false;
276
277                                 logger('Distributing directly '.$target_item["guid"], LOGGER_DEBUG);
278
279                                 // don't send deletions onward for other people's stuff
280
281                                 if ($target_item['deleted'] && !intval($target_item['wall'])) {
282                                         logger('notifier: ignoring delete notification for non-wall item');
283                                         return;
284                                 }
285
286                                 if (strlen($parent['allow_cid'])
287                                         || strlen($parent['allow_gid'])
288                                         || strlen($parent['deny_cid'])
289                                         || strlen($parent['deny_gid'])) {
290                                         $public_message = false; // private recipients, not public
291                                 }
292
293                                 $allow_people = expand_acl($parent['allow_cid']);
294                                 $allow_groups = Group::expand(expand_acl($parent['allow_gid']),true);
295                                 $deny_people  = expand_acl($parent['deny_cid']);
296                                 $deny_groups  = Group::expand(expand_acl($parent['deny_gid']));
297
298                                 // if our parent is a public forum (forum_mode == 1), uplink to the origional author causing
299                                 // a delivery fork. private groups (forum_mode == 2) do not uplink
300
301                                 if ((intval($parent['forum_mode']) == 1) && !$top_level && ($cmd !== 'uplink')) {
302                                         Worker::add($a->queue['priority'], 'Notifier', 'uplink', $item_id);
303                                 }
304
305                                 foreach ($items as $item) {
306                                         $recipients[] = $item['contact-id'];
307                                         $conversants[] = $item['contact-id'];
308                                         // pull out additional tagged people to notify (if public message)
309                                         if ($public_message && strlen($item['inform'])) {
310                                                 $people = explode(',',$item['inform']);
311                                                 foreach ($people as $person) {
312                                                         if (substr($person,0,4) === 'cid:') {
313                                                                 $recipients[] = intval(substr($person,4));
314                                                                 $conversants[] = intval(substr($person,4));
315                                                         } else {
316                                                                 $url_recipients[] = substr($person,4);
317                                                         }
318                                                 }
319                                         }
320                                 }
321
322                                 if (count($url_recipients)) {
323                                         logger('notifier: '.$target_item["guid"].' url_recipients ' . print_r($url_recipients,true));
324                                 }
325
326                                 $conversants = array_unique($conversants);
327
328                                 $recipients = array_unique(array_merge($recipients,$allow_people,$allow_groups));
329                                 $deny = array_unique(array_merge($deny_people,$deny_groups));
330                                 $recipients = array_diff($recipients,$deny);
331
332                                 $conversant_str = dbesc(implode(', ',$conversants));
333                         }
334
335                         // If the thread parent is OStatus then do some magic to distribute the messages.
336                         // We have not only to look at the parent, since it could be a Friendica thread.
337                         if (($thr_parent && ($thr_parent['network'] == NETWORK_OSTATUS)) || ($parent['network'] == NETWORK_OSTATUS)) {
338                                 $diaspora_delivery = false;
339
340                                 logger('Some parent is OStatus for '.$target_item["guid"]." - Author: ".$thr_parent['author-id']." - Owner: ".$thr_parent['owner-id'], LOGGER_DEBUG);
341
342                                 // Send a salmon to the parent author
343                                 $probed_contact = dba::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['author-id']]);
344                                 if (DBM::is_result($probed_contact) && !empty($probed_contact["notify"])) {
345                                         logger('Notify parent author '.$probed_contact["url"].': '.$probed_contact["notify"]);
346                                         $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
347                                 }
348
349                                 // Send a salmon to the parent owner
350                                 $probed_contact = dba::selectFirst('contact', ['url', 'notify'], ['id' => $thr_parent['owner-id']]);
351                                 if (DBM::is_result($probed_contact) && !empty($probed_contact["notify"])) {
352                                         logger('Notify parent owner '.$probed_contact["url"].': '.$probed_contact["notify"]);
353                                         $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
354                                 }
355
356                                 // Send a salmon notification to every person we mentioned in the post
357                                 $arr = explode(',',$target_item['tag']);
358                                 foreach ($arr as $x) {
359                                         //logger('Checking tag '.$x, LOGGER_DEBUG);
360                                         $matches = null;
361                                         if (preg_match('/@\[url=([^\]]*)\]/',$x,$matches)) {
362                                                         $probed_contact = Probe::uri($matches[1]);
363                                                 if ($probed_contact["notify"] != "") {
364                                                         logger('Notify mentioned user '.$probed_contact["url"].': '.$probed_contact["notify"]);
365                                                         $url_recipients[$probed_contact["notify"]] = $probed_contact["notify"];
366                                                 }
367                                         }
368                                 }
369
370                                 // It only makes sense to distribute answers to OStatus messages to Friendica and OStatus - but not Diaspora
371                                 $networks = [NETWORK_OSTATUS, NETWORK_DFRN];
372                         } else {
373                                 $networks = [NETWORK_OSTATUS, NETWORK_DFRN, NETWORK_DIASPORA, NETWORK_MAIL];
374                         }
375                 } else {
376                         $public_message = false;
377                 }
378
379                 // If this is a public message and pubmail is set on the parent, include all your email contacts
380                 if (function_exists('imap_open') && !Config::get('system','imap_disabled')) {
381                         if (!strlen($target_item['allow_cid']) && !strlen($target_item['allow_gid'])
382                                 && !strlen($target_item['deny_cid']) && !strlen($target_item['deny_gid'])
383                                 && intval($target_item['pubmail'])) {
384                                 $r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `network` = '%s'",
385                                         intval($uid),
386                                         dbesc(NETWORK_MAIL)
387                                 );
388                                 if (DBM::is_result($r)) {
389                                         foreach ($r as $rr) {
390                                                 $recipients[] = $rr['id'];
391                                         }
392                                 }
393                         }
394                 }
395
396                 if (($cmd == Delivery::RELOCATION)) {
397                         $r = $recipients_relocate;
398                 } else {
399                         if ($followup) {
400                                 $recipients = $recipients_followup;
401                         }
402                         $condition = ['id' => $recipients, 'self' => false,
403                                 'blocked' => false, 'pending' => false, 'archive' => false];
404                         if (!empty($networks)) {
405                                 $condition['network'] = $networks;
406                         }
407                         $contacts = dba::select('contact', ['id', 'url', 'network'], $condition);
408                         $r = dba::inArray($contacts);
409                 }
410
411                 // delivery loop
412                 if (DBM::is_result($r)) {
413                         foreach ($r as $contact) {
414                                 logger("Deliver ".$target_item["guid"]." to ".$contact['url']." via network ".$contact['network'], LOGGER_DEBUG);
415
416                                 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
417                                                 'Delivery', $cmd, $item_id, (int)$contact['id']);
418                         }
419                 }
420
421                 // send salmon slaps to mentioned remote tags (@foo@example.com) in OStatus posts
422                 // They are especially used for notifications to OStatus users that don't follow us.
423                 if (!Config::get('system', 'dfrn_only') && count($url_recipients) && ($public_message || $push_notify) && $normal_mode) {
424                         $slap = OStatus::salmon($target_item, $owner);
425                         foreach ($url_recipients as $url) {
426                                 if ($url) {
427                                         logger('notifier: urldelivery: ' . $url);
428                                         $deliver_status = Salmon::slapper($owner, $url, $slap);
429                                         /// @TODO Redeliver/queue these items on failure, though there is no contact record
430                                 }
431                         }
432                 }
433
434                 if ($public_message) {
435                         $r1 = [];
436
437                         if ($diaspora_delivery) {
438                                 $r1 = q("SELECT `batch`, ANY_VALUE(`id`) AS `id`, ANY_VALUE(`name`) AS `name`, ANY_VALUE(`network`) AS `network`
439                                         FROM `contact` WHERE `network` = '%s' AND `batch` != ''
440                                         AND `uid` = %d AND `rel` != %d AND NOT `blocked` AND NOT `pending` AND NOT `archive` GROUP BY `batch`",
441                                         dbesc(NETWORK_DIASPORA),
442                                         intval($owner['uid']),
443                                         intval(CONTACT_IS_SHARING)
444                                 );
445
446                                 // Fetch the participation list
447                                 // The function will ensure that there are no duplicates
448                                 $r1 = Diaspora::participantsForThread($item_id, $r1);
449
450                                 // Add the relay to the list, avoid duplicates
451                                 if (!$followup) {
452                                         $r1 = Diaspora::relayList($item_id, $r1);
453                                 }
454                         }
455
456                         $condition = ['network' => NETWORK_DFRN, 'uid' => $owner['uid'], 'blocked' => false,
457                                 'pending' => false, 'archive' => false, 'rel' => [CONTACT_IS_FOLLOWER, CONTACT_IS_FRIEND]];
458                         $r2 = dba::inArray(dba::select('contact', ['id', 'name', 'network'], $condition));
459
460                         $r = array_merge($r2, $r1);
461
462                         if (DBM::is_result($r)) {
463                                 logger('pubdeliver '.$target_item["guid"].': '.print_r($r,true), LOGGER_DEBUG);
464
465                                 foreach ($r as $rr) {
466                                         // except for Diaspora batch jobs
467                                         // Don't deliver to folks who have already been delivered to
468
469                                         if (($rr['network'] !== NETWORK_DIASPORA) && (in_array($rr['id'], $conversants))) {
470                                                 logger('notifier: already delivered id=' . $rr['id']);
471                                                 continue;
472                                         }
473
474                                         if (!in_array($cmd, [Delivery::MAIL, Delivery::SUGGESTION]) && !$followup) {
475                                                 logger('notifier: delivery agent: '.$rr['name'].' '.$rr['id'].' '.$rr['network'].' '.$target_item["guid"]);
476                                                 Worker::add(['priority' => $a->queue['priority'], 'created' => $a->queue['created'], 'dont_fork' => true],
477                                                                 'Delivery', $cmd, $item_id, (int)$rr['id']);
478                                         }
479                                 }
480                         }
481
482                         $push_notify = true;
483                 }
484
485                 // Notify PuSH subscribers (Used for OStatus distribution of regular posts)
486                 if ($push_notify) {
487                         logger('Activating internal PuSH for item '.$item_id, LOGGER_DEBUG);
488
489                         // Handling the pubsubhubbub requests
490                         PushSubscriber::publishFeed($owner['uid'], $a->queue['priority']);
491                 }
492
493                 logger('notifier: calling hooks for ' . $cmd . ' ' . $item_id, LOGGER_DEBUG);
494
495                 if ($normal_mode) {
496                         Addon::forkHooks($a->queue['priority'], 'notifier_normal', $target_item);
497                 }
498
499                 Addon::callHooks('notifier_end',$target_item);
500
501                 return;
502         }
503 }