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