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