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